Created
July 16, 2020 07:50
-
-
Save magicleon94/5df43984365b6fabe9cd5e62b7483f0f to your computer and use it in GitHub Desktop.
Flutter FutureBuilder with Completer 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 'package:flutter/material.dart'; | |
import 'dart:async'; | |
final Color darkBlue = Color.fromARGB(255, 18, 32, 47); | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue), | |
debugShowCheckedModeBanner: false, | |
home: Scaffold( | |
body: Center( | |
child: CompleterExample(), | |
), | |
), | |
); | |
} | |
} | |
class CompleterExample extends StatefulWidget { | |
@override | |
_CompleterExampleState createState() => _CompleterExampleState(); | |
} | |
class _CompleterExampleState extends State<CompleterExample> { | |
final listCompleter = Completer<List<int>>(); | |
Future<void> _initList() async { | |
await Future.delayed(Duration(seconds: 1)); //simulate the delay | |
final result = List.generate(10, (index) => index); | |
listCompleter.complete(result); | |
} | |
@override | |
void initState() { | |
super.initState(); | |
_initList(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return FutureBuilder<List<int>>( | |
future: listCompleter.future, | |
builder: (context, snapshot) { | |
if (!snapshot.hasData) { | |
return Center( | |
child: CircularProgressIndicator(), | |
); | |
} else { | |
final list = snapshot.data; | |
return ListView.builder( | |
itemCount: list.length, | |
itemBuilder: (context, index) => Text(list[index].toString()), | |
); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment