Where to build data source for display in a screen in flutter
315
You're looking for a FutureBuilder
as shown in the FlutterFire documentation on reading data using get
and the example of using a ListView
in that same page:
@override
Widget build(BuildContext context) {
return FutureBuilder<QuerySnapshot>(
future: FirebaseFirestore.instance.collection('ads').get(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.connectionState == ConnectionState.done) {
return new ListView(
children: snapshot.data.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data = document.data() as Map<String, dynamic>;
return new ListTile(
title: new Text(data['_iname']),
);
}).toList(),
);
}
return Text("loading");
},
);
}
Author by
Leo
Updated on December 24, 2022Comments
-
Leo over 1 year
I have a screen in flutter
SearchFoodItemPage
It is a stateful widget in a file namedsearch_food_item_page.dart
. My purpose is to fetch list of items from firebase and display it on this screen. I want to fetch data from firebase when this screen starts. I want to do all the data fetching in this file.For that I tried fetching data in
build
method of the the widget. But we cannot add async modifier to the build method hence it did not work. I would like to know where to build the data source for this purpose.Below is the code snippet for this screen.
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; // new import 'package:firebase_auth/firebase_auth.dart'; // new class SearchFoodItemPage extends StatefulWidget { SearchFoodItemPage({Key? key, required this.title}) : super(key: key); final String title; @override _SearchFoodItemPageState createState() => _SearchFoodItemPageState(); } class _SearchFoodItemPageState extends State<SearchFoodItemPage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { List<String> _adsList = []; /////////////////////////////////////////////////////////////// code for building data source print("****************************************************************************"); await FirebaseFirestore.instance .collection('ads') .get() .then((QuerySnapshot querySnapshot) { querySnapshot.docs.forEach((doc) { print(doc["_iname"]); _adsList.add( doc["_iname"] as String ); }); }); print('${_adsList.length}'); for (final foodname in _adsList) { print('${foodname.toString()}'); } /////////////////////////////////////////////////////////////// return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ // AdvertisementForm(), Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
Thanks!
-
Leo almost 3 yearsThanks very much for sharing! I submitted edit for changing DocumentSnapshot to QuerySnapshot in first two occurances and removed "has data " check due to synatx error. Feel free to edit if it can be further improved. Thanks!