— Android, Mobile, Flutter, Firebase — 1 min read
Sometimes while making a new screen, we need to have the data first and then show it on the widget. It can be getting data from the Internet, reading data from Firebase, or loading from a file. Here are some ways to help us prepare the data before showing it on the widget
FutureBuilder
:1FutureBuilder<VOAAudio?>(2 future: FirestoreProvider.getFirestoreAudioObject(ObjectId), // Load your data here3 builder: (context, snapshot) {4 if (snapshot.hasData) {5 _pageManager.init(snapshot.data!.audio!);6 return SafeArea(7 child: Column(children: <Widget>[8 Expanded(9 child: Stack(10 children: [...]11 } else if (snapshot.hasError) {12 return Text('${snapshot.error}');13 }14 // By default, show a loading spinner.15 return new Center(child: const CircularProgressIndicator());
With this solution, our application gets new data whenever the Widget gets updated by calling the build
function. Sometimes, It can be a problem. We can just load the data once in initState()
function by the next solution
initState()
:1// First define your async loading function2Future<VOAAudio?> loadFirestoreAudioObject() async {3 VOAAudio? voaAudio = await FirestoreProvider.getFirestoreAudioObject(ObjectId);4 return voaAudio;5}6
7// Then call the async function in initState with then8@override9void initState() {10 super.initState();11 _pageManager = PageManager();12 loadFirestoreAudioObject().then((value) {13 voaLoaded = true;14 if(value != null) {15 _voaAudio = value;16 } else {17 voaLoadingError = false;18 }19 setState(() {});20 });21}22
23@override24Widget build(BuildContext context) {25return MaterialApp(26 home: Scaffold(27 body: LayoutBuilder(builder: (context, constraints) {28
29 // Update your View after loading data30 if(voaLoadingError){31 return const Text(“Connection error!”);32 } else if(voaLoading){33 return SafeArea(…)34 }35
36 // By default, show a loading spinner.37 return const Center(child: CircularProgressIndicator());38 }),)39);40}