Created
January 6, 2022 21:46
-
-
Save Roaa94/25c827b132e69f53f44be207a8ded78c to your computer and use it in GitHub Desktop.
Future builder example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:flutter/material.dart'; | |
import 'package:http/http.dart' as http; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Example', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.teal, | |
), | |
home: StarterPage(), | |
); | |
} | |
} | |
class StarterPage extends StatefulWidget { | |
@override | |
State<StarterPage> createState() => _StarterPageState(); | |
} | |
class _StarterPageState extends State<StarterPage> { | |
Future<List<dynamic>> _getPolicy() async { | |
final url = | |
Uri.parse('https://jsonplaceholder.typicode.com/todos?userId=1'); | |
try { | |
final response = await http.get(url); | |
return json.decode(response.body); | |
} catch (error) { | |
print('---error-'); | |
rethrow; | |
} | |
} | |
late Future<List<dynamic>> _loadedProducts; | |
@override | |
void initState() { | |
_loadedProducts = _getPolicy(); | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: const Text('Starter Page')), | |
body: FutureBuilder<List<dynamic>>( | |
future: _loadedProducts, | |
builder: (context, AsyncSnapshot<List<dynamic>> snapshot) { | |
if (snapshot.hasData && | |
snapshot.data != null && | |
snapshot.data!.isNotEmpty) { | |
return AnimatedList( | |
initialItemCount: snapshot.data!.length, | |
itemBuilder: | |
(BuildContext context, int index, Animation animation) { | |
return Text(snapshot.data![index]['title']); | |
}, | |
); | |
} else if (snapshot.hasError) { | |
return Text("${snapshot.error}"); | |
} | |
// By default, show a loading spinner. | |
return const CircularProgressIndicator(); | |
}, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment