Flutter FutureBuilder Widget - API call using FutureBuilder | Flutter Tutorial
Source Code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<int> getData() async {
final data = await http.get(Uri.parse(
"http://www.randomnumberapi.com/api/v1.0/random?min=100&max=1000&count=1"));
final body = json.decode(data.body);
int number = (body as List).first;
return number;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: SafeArea(
child: Center(
child: FutureBuilder(
future: getData(),
builder: ((context, snapshot) {
if (snapshot.data == ConnectionState.waiting) {
return const CircularProgressIndicator();
} else if (snapshot.hasError) {
return const Text("Error");
} else if (snapshot.hasData) {
return Text(
"${snapshot.data}",
style: const TextStyle(
fontSize: 62, fontWeight: FontWeight.bold),
);
} else {
return const CircularProgressIndicator();
}
})),
),
),
),
);
}
}
Comments
Post a Comment