flutter firebase database and ListView builder issue - firebase

I suppose to show each item of my shopList in ListView, but I can't find out the reason why it keep showing the same record. Please help to solve this issue.
Here with the code, get data from firebase database.
databaseReference.once().then((DataSnapshot snapshot) {
Map<dynamic, dynamic> getMap = snapshot.value;
getMap.forEach((k, v) {
Map<dynamic, dynamic> f = v;
shop.key = k;
shop.shopName = f["ShopName"];
shop.tel = f["ShopTel"];
shop.address = f["ShopAddress"];
shop.thumbnail = f["Thumbnail"];
debugPrint(k);
shopList.add(shop);
debugPrint(shopList[shopList.length-1].shopName);
});
});
DebugPrint result:
flutter: -LLySYDHHHx9WtCvKPrO
flutter: shop1111
flutter: -LLyXwR0nnAcx6_H4cYy
flutter: shop2222
Here with the database:
Here with the code for ListView:
child: Flexible(
child: new ListView.builder(
itemCount: shopList.length,
itemBuilder: (context, index) {
return new Card(
color: Colors.red,
//elevation: 2.0,
child: new ListTile(
title: new Text("Name: ${shopList[index].key}"),
),
);
}),
),
the result of simulator:

Try this.
That's what I would do
Shop.dart
class Shop {
String key;
String name;
String address;
String phone;
String thumbnail;
Shop(this.name,this.address,this.phone,this.thumbnail);
Shop.fromSnapshot(DataSnapshot snapshot)
: key = snapshot.key,
name = snapshot.value["name"],
address= snapshot.value["address"],
phone= snapshot.value["phone"],
thumbnail= snapshot.value["thumbnail"];
toJson() {
return {
"name": name,
"address": address,
"phone": phone,
"thumbnail": thumbnail,
};
}
}
main.dart
List<Shop> itemsShop = List();
Shop itemShop;
DatabaseReference itemRefShop;
#override
void initState() {
super.initState();
itemShop = Shop("", "", "", "");
final FirebaseDatabase database = FirebaseDatabase.instance;
itemRefShop = database.reference().child('Shop');
itemRefShop.onChildAdded.listen(_onEntryAddedShop);
itemRefShop.onChildChanged.listen(_onEntryChangedShop);
}
_onEntryAddedShop(Event event) {
setState(() {
itemsShop.add(Shop.fromSnapshot(event.snapshot));
});
}
_onEntryChangedShop(Event event) {
var old = itemsShop.singleWhere((entry) {
return entry.key == event.snapshot.key;
});
setState(() {
itemsShop[Shop.indexOf(old)] = Shop.fromSnapshot(event.snapshot);
});
}
#override
Widget build(BuildContext context) {
return new Container(
child: new Column(
children: <Widget>[
new Flexible(
child: new FirebaseAnimatedList(
query: itemRefShop,
itemBuilder:(_, DataSnapshot snapshot, Animation<double> animation, int index){
return new ListTile(
title: new Text(snapshot.value['name']),
subtitle: new Text(itemsShop[index].address),
);
}
),
]
),
);
}
}

Related

Lazy Loading list view builder in Flutter with Helper.Provider-Model

what I'm trying to do is use lazy loading of elements in list view builder in flutter.
I used also the Provider, helpers and model paradigma and I'm trying to load some dishes from my db in firestore.
I found different solution for implementing lazy loading such as this. But I obtain an error.
Below the code:
Helpers
class DishServices{
String collection = "dishes";
FirebaseFirestore _firestore = FirebaseFirestore.instance;
String subcollection = "ingredients";
List<DishModel> dishes = [];
QuerySnapshot collectionState;
Future<List<DishModel>> getLazyDishes() async
{
var collectionData = _firestore.collection(collection).orderBy("name").limit(2);
fetchDocuments(collectionData);
return dishes;
}
Future<List<DishModel>> getLazyDishesNext() async {
// Get the last visible document
var lastVisible = collectionState.docs[collectionState.docs.length-1];
var collectionData = FirebaseFirestore.instance
.collection(collection)
.orderBy("name").startAfterDocument(lastVisible).limit(3);
fetchDocuments(collectionData);
return dishes;
}
fetchDocuments(Query collection){
collection.get().then((value) {
collectionState = value; // store collection state to set where to start next
value.docs.forEach((element) {
dishes.add(DishModel.fromSnapshot(element));
});
});
}
}
Provider
class DishProvider with ChangeNotifier{
DishServices _dishServices = DishServices();
List<DishModel> dishes = [];
List<DishModel> dishesLazyNext = [];
DishProvider.initialize(){
_loadDishes();
// searchIngredient(ingredientName:"cime");
}
_loadDishes() async{
dishes = await _dishServices.getLazyDishes();
notifyListeners();
}
Future loadNextLazyDishes()async{
dishesLazyNext = await _dishServices.getLazyDishesNext();
dishes = dishes + dishesLazyNext;
notifyListeners();
}
}
Main.dart
oid main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MultiProvider(providers: [
ChangeNotifierProvider.value(value: DishProvider.initialize())
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'MyApp',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: ScreensController()
)));
}
Finally my build is :
class _MainHomeState extends State<MainHome> {
ScrollController scrollController = ScrollController();
#override
void initState() {
super.initState();
final dishProvider = Provider.of<DishProvider>(context);
scrollController.addListener(() {
if (scrollController.position.atEdge) {
if (scrollController.position.pixels == 0)
print('ListView scroll at top');
else {
print('ListView scroll at bottom');
dishProvider.loadNextLazyDishes(); // Load next documents
}
}
});
}
#override
Widget build(BuildContext context) {
final dishProvider = Provider.of<DishProvider>(context);
//atest.loadA();
return Scaffold(
body: SafeArea(
child: ListView(
children: <Widget>[
OtherElement(),
Container(
child: ListView.builder(
controller: scrollController,
itemCount: dishProvider.dishes.length,
shrinkWrap: true,
itemBuilder: (_,index){
return DishWidget(
dishModel: dishProvider.dishes[index],
);
}),
),
],
),
),
);
}
}
this is the error that return when I try to run the app
How I can fix it?
Just move the scroll listener to your build:
class _MainHomeState extends State<MainHome> {
ScrollController scrollController = ScrollController();
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
final dishProvider = Provider.of<DishProvider>(context);
scrollController.addListener(() {
if (scrollController.position.atEdge) {
if (scrollController.position.pixels == 0)
print('ListView scroll at top');
else {
print('ListView scroll at bottom');
dishProvider.loadNextLazyDishes(); // Load next documents
}
}
});
//atest.loadA();
return Scaffold(
body: SafeArea(
child: ListView(
children: <Widget>[
OtherElement(),
Container(
child: ListView.builder(
controller: scrollController,
itemCount: dishProvider.dishes.length,
shrinkWrap: true,
itemBuilder: (_,index){
return DishWidget(
dishModel: dishProvider.dishes[index],
);
}),
),
],
),
),
);
}
}

Flutter Firebase Get data from docs and convert map to List?

I want to fetch data from Firebase and show it.
No data is visible.
There is a problem with the getProduct function. How can I do it?
Please kind answer.
====Build result =========
===== Model ===
class Product {
String id;
String name;
String category;
String image;
list images;
String desc;
String price;
Timestamp createdAt;
Timestamp updatedAt;
Product();
Product.fromMap(Map<String, dynamic> data) {
id = data['id'];
name = data['name'];
category = data['category'];
image = data['image'];
images = data['images'];
desc = data['desc'];
price = data['price'];
createdAt = data['createdAt'];
updatedAt = data['updatedAt'];
}
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'category': category,
'images': images,
'image': image,
'desc': desc,
'price': price,
'createdAt': createdAt,
'updatedAt': updatedAt
};
}
}
========= Product Notifier Lib =============
class ProductNotifier with ChangeNotifier {
List<Product> _productList = [];
Product _currentProduct;
UnmodifiableListView<Product> get productList =>
UnmodifiableListView(_productList);
Product get currentProduct => _currentProduct;
set productList(List<Product> productList) {
_productList = productList;
notifyListeners();
}
set currentProduct(Product product) {
_currentProduct = product;
notifyListeners();
}
addProduct(Product product) {
_productList.insert(0, product);
notifyListeners();
}
deleteProduct(Product product) {
_productList.removeWhere((_product) => _product.id == product.id);
notifyListeners();
}
}
========= Get Products API ===============
There seems to be a problem with the code below. What should I do?
getProducts(ProductNotifier productNotifier) async {
QuerySnapshot snapshot = await FirebaseFirestore.instance
.collection('Products')
.orderBy("createdAt", descending: true)
.get();
List<Product> _productList = [];
snapshot.docs.forEach((document) {
Product product = Product.fromMap(
document.data());
_productList.add(product);
});
productNotifier.productList = _productList;
}
========= Product Feed Page =============
class ProductFeed extends StatefulWidget {
#override
_ProductState createState() => _ProductState();
}
class _ProductState extends State<ProductFeed> {
#override
void initState() {
ProductNotifier productNotifier =
Provider.of<ProductNotifier>(context, listen: false);
getProducts(productNotifier);
super.initState();
}
#override
Widget build(BuildContext context) {
AuthNotifier authNotifier = Provider.of<AuthNotifier>(context);
ProductNotifier productNotifier = Provider.of<ProductNotifier>(context);
Future<void> _refreshList() async {
getProducts(productNotifier);
}
return Scaffold(
appBar: AppBar(
title: Text('Product Feed'
),
actions: <Widget>[
// action button
FlatButton(
onPressed: () => signOut(authNotifier),
child: Text(
"Logout",
style: TextStyle(fontSize: 20, color: Colors.white),
),
),
],
),
body: new RefreshIndicator(
child: ListView.separated(
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: Image.network(
productNotifier.productList[index].image != null
? productNotifier.productList[index].image
: 'https://www.testingxperts.com/wp-content/uploads/2019/02/placeholder-img.jpg',
width: 120,
fit: BoxFit.fitWidth,
),
title: Text(productNotifier.productList[index].name),
subtitle: Text(productNotifier.productList[index].category),
onTap: () {
productNotifier.currentProduct =
productNotifier.productList[index];
Navigator.of(context)
.push(MaterialPageRoute(builder: (BuildContext context) {
return Text('Product Detail'); //FoodDetail();
}));
},
);
},
itemCount: productNotifier.productList.length,
separatorBuilder: (BuildContext context, int index) {
return Divider(
color: Colors.black,
);
},
),
onRefresh: _refreshList,
),
);
}
}

Flutter ListView is not updating when the list items are changed

I started learning Flutter. I am developing a simple application using it. Now, I am developing a feature where my application will display the records from the SQLite database and where the user adds the new records into the SQLite database. But my ListView is displaying the blank screen.
I have a class called DatabaseHelper with the following code.
class DatabaseHelper {
static DatabaseHelper _databaseHelper;
Database _database;
String noteTable = 'note_table';
String colId = 'id';
String colTitle = 'title';
String colDescription = 'description';
String colPriority = 'priority';
String colDate = 'date';
DatabaseHelper._createInstance();
factory DatabaseHelper() {
if (_databaseHelper == null) {
_databaseHelper = DatabaseHelper._createInstance();
}
return _databaseHelper;
}
Future<Database> get database async {
if (_database == null) {
_database = await initializeDatabase();
}
return _database;
}
Future<Database> initializeDatabase() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'notes.db';
var notesDatabase = await openDatabase(path, version: 1, onCreate: _createDB);
return notesDatabase;
}
void _createDB(Database db, int newVersion) async {
await db.execute('CREATE TABLE $noteTable($colId INTEGER PRIMARY KEY AUTOINCREMENT, $colTitle TEXT, $colDescription TEXT, $colPriority INTEGER, $colDate TEXT)');
}
Future<List<Map<String, dynamic>>> getNoteMapList() async {
Database db = await this.database;
return await db.query(noteTable, orderBy: '$colPriority ASC');
}
Future<int> insertNote(Note note) async {
Database db = await this.database;
return await db.insert(noteTable, note.toMap());
}
Future<int> updateNote(Note note) async {
var db = await this.database;
return await db.update(noteTable, note.toMap(), where: '$colId = ?', whereArgs: [note.id]);
}
Future<int> deleteNote(int id) async {
var db = await this.database;
return await db.rawDelete('DELETE FROM $noteTable WHERE $colId = $id');
}
Future<int> getCount() async {
Database db = await this.database;
List<Map<String, dynamic>> x = await db.rawQuery('SELECT COUNT(*) FROM $noteTable');
return Sqflite.firstIntValue(x);
}
}
Then I have a widget called NoteList with the following code where the list of items are displayed.
class NoteList extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _NoteListState();
}
}
class _NoteListState extends State<NoteList> {
List<Note> _notes = [];
int _count = 0;
DatabaseHelper _databaseHelper = DatabaseHelper();
_NoteListState() {
this._notes = getNotes();
this._count = _notes.length;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Notes"),),
body: Container(
child: getListView(context),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
navigateToNoteForm("Add Note");
},
),
);
}
Widget getListView(BuildContext context) {
return ListView.builder(
itemCount: _count,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
backgroundColor: _notes[index].priority == 1? Colors.yellow: Colors.red,
child: Icon(_notes[index].priority == 1 ? Icons.arrow_right : Icons.add),
),
title: Text(_notes[index].title),
subtitle: Text(_notes[index].date),
trailing: Icon(Icons.delete),
onTap: () {
navigateToNoteForm("Edit Note", _notes[index]);
},
);
});
}
void navigateToNoteForm(String pageTitle, [Note note]) async {
bool result = await Navigator.push(context, MaterialPageRoute(builder: (context) {
return NoteForm(pageTitle, note);
}));
if (result) {
setState(() {
debugPrint("Updating list");
_notes = getNotes();
_count = _notes.length;
});
}
}
List<Note> getNotes() {
List<Note> notes = List<Note>();
Future<List<Map<String, dynamic>>> notesFuture = _databaseHelper.getNoteMapList();
notesFuture.then((notesMap) {
debugPrint("Total notes found in the database ${notesMap.length}");
notesMap.forEach((map) {
notes.add(Note.fromMapObject(map));
});
});
return notes;
}
}
Then I also have another widget class called NoteForm with the following code.
class NoteForm extends StatefulWidget {
String _title = "";
Note _note = null;
NoteForm(String title, [Note note]) {
this._title = title;
this._note = note;
}
#override
State<StatefulWidget> createState() {
return _NoteFormState();
}
}
class _NoteFormState extends State<NoteForm> {
double _minimumPadding = 15.0;
var _priorities = [ 1, 2 ];
var _titleController = TextEditingController();
var _descriptionController = TextEditingController();
var _dateController = TextEditingController();
DatabaseHelper _databaseHelper = DatabaseHelper();
var _selectedPriority = 1;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget._title),),
body: Builder(
builder: (scaffoldContext) => Form(
child: Column(
children: <Widget>[
Container(
child: Padding(
padding: EdgeInsets.all(_minimumPadding),
child: TextFormField(
controller: _titleController,
decoration: InputDecoration(
labelText: "Title",
hintText: "Enter title"
),
),
),
),
Container(
child: Padding(
padding: EdgeInsets.all(_minimumPadding),
child: TextFormField(
controller: _descriptionController,
decoration: InputDecoration(
labelText: "Description",
hintText: "Enter description"
),
),
)
),
Container(
child: Padding(
padding: EdgeInsets.all(_minimumPadding),
child: TextFormField(
controller: _dateController,
decoration: InputDecoration(
labelText: "Date",
hintText: "Enter date"
),
),
),
),
Container(
child: Padding(
padding: EdgeInsets.all(_minimumPadding),
child: DropdownButton<int>(
value: _selectedPriority,
items: _priorities.map((dropdownItem) {
return DropdownMenuItem<int>(
value: dropdownItem,
child: Text(dropdownItem == 1? "Low": "High"),
);
}).toList(),
onChanged: (int newSelectedValue) {
setState(() {
_selectedPriority = newSelectedValue;
});
},
),
),
),
Container(
child: Padding(
padding: EdgeInsets.all(_minimumPadding),
child: RaisedButton(
child: Text(
"Save"
),
onPressed: () {
_save(scaffoldContext);
},
),
),
)
],
),
),
)
);
}
void _save(BuildContext context) async {
Note note = Note();
note.title = _titleController.text;
note.description = _descriptionController.text;
note.date = _dateController.text;
note.priority = _selectedPriority;
if (widget._note != null && widget._note.id!=null) {
//update
_databaseHelper.updateNote(note);
this.showSnackBar(context, "Note has been updated.");
} else {
//create
_databaseHelper.insertNote(note);
this.showSnackBar(context, "Note has been added.");
}
closeForm(context);
}
void showSnackBar(BuildContext context, String message) {
var snackBar = SnackBar(
content: Text(message),
action: SnackBarAction(
label: "UNDO",
onPressed: () {
},
),
);
Scaffold.of(context).showSnackBar(snackBar);
}
void closeForm(BuildContext context) {
Navigator.pop(context, true);
}
}
When I run my application, it is just displaying the blank screen as follows.
As you can see I am logging out the number of records returned from the database using debugPrint method. It is saying that there are 6 records within the database. It is just not displaying the records. What is wrong with my code and how can I fix it?
As i mention in comment that was happening because of async task take some time to perform and if you do not keep it async then setState function execute before actual data load or set.
So Following changes solve your issue.
make getNotes async method And
getNotes().then((noteresponce){ setState((){ _notes=noteresponce; _count = _notes.length;} });

Loading data from Firebase into a DropdownButton in Flutter

I'm new in Flutter with Firebase and I'm trying to load some arrays stored in Firebase into a DropdownButton.
This piece of code works when a I call it from a button. It returns a list of drinks that I can print on the screen:
Future<List<String>> get drinks async {
QuerySnapshot docs = await _constantes.getDocuments();
List<String> res = List();
List<Map<String, dynamic>> datos = List();
for (var d in docs.documents) {
datos.add(d.data);
}
for (var d in datos[0]['drinks'].toList()) {
res.add(d.toString());
}
return res;
}
But my problem is that I'd like to load this list into a DropdownButton, so the user could choose one of the drinks when the app shows him the form :
DropdownButtonFormField(
hint: Text('Choose a drink'),
value: _currentDrink ?? 'Water',
items: _db.drinks.then((drinks) {
List<DropdownMenuItem> datos = List();
for (var d in drinks) {
datos.add(DropdownMenuItem(
value: d,
child: Text(d),
));
}
return datos;
}),
onChanged: (val) => setState(() => _currentDrink = val),
),
But it doesn't work because the result is a Future.
How could I fix it?
Thanks.
Wrap it in a StreamBuilder. Instead of querying using _constantes.getDocuments() return the stream from _constantes.snapshots() assuming _constantes is your firebase collection:
StreamBuilder<List<DocumentSnapshot>>(
stream: _drinkStream,
builder: (context, snapshot) {
return snapshot.hasData
? DropdownButton(
onChanged: (value) {},
items: [
for (var child in snapshot.data)
DropdownMenuItem(
child: Text(
child.data['name'],
),
value: child,
),
],
)
: Container();
},
)
Assign an empty list [] to dropdown until drinks are fetched and when fetched we will assign drinks list.Drinks list will get items after our future is completed.You need to call this future in initState of your method so when page is opened it fetches drinks and then assigns it to the drinks list.Dropdown will remain empty until drinks are fetched.
(Incase you want to show progressindicator on dropdown until drinks are fetched wrap dropdown in a future builder)
List<String> drinks = List();
Future<List<String>> get drinks async {
QuerySnapshot docs = await _constantes.getDocuments();
List<String> res = List();
List<Map<String, dynamic>> datos = List();
for (var d in docs.documents) {
datos.add(d.data);
}
for (var d in datos[0]['drinks'].toList()) {
res.add(d.toString());
}
setState(() {
drinks = res;
});
return res;
}
DropdownButtonFormField(
hint: Text('Choose a drink'),
value: _currentDrink ?? 'Water',
items: drinks == null? []: drinks.map((drink) {
return DropdownMenuItem<String>(
child: Text(drink),
value: drink,
);
}).toList(),
onChanged: (val) => setState(() => _currentDrink = val),
),
you can build drop down widget after you get data from your firebase and if you want to make show water before data is load or not data found then following solutions could be best for you.
in method comment part is for your case and un comment part is for demo.
class DeleteWidget extends StatefulWidget {
const DeleteWidget({Key key}) : super(key: key);
#override
_DeleteWidgetState createState() => _DeleteWidgetState();
}
class _DeleteWidgetState extends State<DeleteWidget> {
String initdata = 'water';
List<String> _getdata = List();
#override
void initState() {
super.initState();
getdatafromAPI();
}
void getdatafromAPI() async {
/*
_db.drinks.then((drinks){
setState((){
_getdata.addAll(drinks);
initdata = _getdata[0];
});
});
*/
await Future.delayed(Duration(seconds: 1));
setState(() {
_getdata.addAll(['coffee', 'tea', 'greentea']);
initdata = _getdata[0];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('test app'),
),
body: Container(
child: Center(
child: DropdownButton(
items: _getdata.length > 0
? _getdata.map((e) {
return DropdownMenuItem<String>(
child: Text(e.toString()),
value: e.toString(),
);
}).toList()
: [
DropdownMenuItem<String>(
child: Text("water"),
value: 'water',
)
],
value: initdata,
onChanged: (value) {
setState(() {
initdata = value;
});
},
),
),
),
);
}
}

how to get data from firebase in flutter

I am building a flutter app and using cloud-firestore,
this is how my database looks like
I want a function that retrieves all documents in the collection called "Driver List" in an array of strings
that what I had already used but it gets them back in a listview in a new screen
class DriverList extends StatelessWidget {#overrideWidget build(BuildContext context) {
return new StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('DriverList').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) return new Text('Loading...');
return new ListView(
children: snapshot.data.documents.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document['name']),
subtitle: new Text(document['phone']),
);
}).toList(),
);
},
);
}
}
This has some additional logic to remove potentially duplicate records, but you can use something like the following to retrieve data from Firestore.
We get access to a collection reference, then list the results of the query, then create local model objects for the data returned by Firestore, and then we return the a list of those model objects.
static Future<List<AustinFeedsMeEvent>> _getEventsFromFirestore() async {
CollectionReference ref = Firestore.instance.collection('events');
QuerySnapshot eventsQuery = await ref
.where("time", isGreaterThan: new DateTime.now().millisecondsSinceEpoch)
.where("food", isEqualTo: true)
.getDocuments();
HashMap<String, AustinFeedsMeEvent> eventsHashMap = new HashMap<String, AustinFeedsMeEvent>();
eventsQuery.documents.forEach((document) {
eventsHashMap.putIfAbsent(document['id'], () => new AustinFeedsMeEvent(
name: document['name'],
time: document['time'],
description: document['description'],
url: document['event_url'],
photoUrl: _getEventPhotoUrl(document['group']),
latLng: _getLatLng(document)));
});
return eventsHashMap.values.toList();
}
Source: https://github.com/dazza5000/austin-feeds-me-flutter/blob/master/lib/data/events_repository.dart#L33
Getting one time data:
var collection = FirebaseFirestore.instance.collection('DriverList');
var querySnapshot = await collection.get();
for (var queryDocumentSnapshot in querySnapshot.docs) {
Map<String, dynamic> data = queryDocumentSnapshot.data();
var name = data['name'];
var phone = data['phone'];
}
Getting data each time it changes, using a StreamBuilder:
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance.collection('DriverList').snapshots(),
builder: (_, snapshot) {
if (snapshot.hasError) return Text('Error = ${snapshot.error}');
if (snapshot.hasData) {
final docs = snapshot.data!.docs;
return ListView.builder(
itemCount: docs.length,
itemBuilder: (_, i) {
final data = docs[i].data();
return ListTile(
title: Text(data['name']),
subtitle: Text(data['phone']),
);
},
);
}
return Center(child: CircularProgressIndicator());
},
)
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class LoadDataFromFirestore extends StatefulWidget {
#override
_LoadDataFromFirestoreState createState() => _LoadDataFromFirestoreState();
}
class _LoadDataFromFirestoreState extends State<LoadDataFromFirestore> {
#override
void initState() {
super.initState();
getDriversList().then((results) {
setState(() {
querySnapshot = results;
});
});
}
QuerySnapshot querySnapshot;
#override
Widget build(BuildContext context) {
return Scaffold(
body: _showDrivers(),
);
}
//build widget as prefered
//i'll be using a listview.builder
Widget _showDrivers() {
//check if querysnapshot is null
if (querySnapshot != null) {
return ListView.builder(
primary: false,
itemCount: querySnapshot.documents.length,
padding: EdgeInsets.all(12),
itemBuilder: (context, i) {
return Column(
children: <Widget>[
//load data into widgets
Text("${querySnapshot.documents[i].data['activation']}"),
Text("${querySnapshot.documents[i].data['car1']}"),
Text("${querySnapshot.documents[i].data['car2']}"),
Text("${querySnapshot.documents[i].data['car5']}"),
Text("${querySnapshot.documents[i].data['name']}"),
Text("${querySnapshot.documents[i].data['phone']}"),
],
);
},
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
}
//get firestore instance
getDriversList() async {
return await Firestore.instance.collection('DriversList').getDocuments();
}
}
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
StreamBuilder(
stream:
FirebaseFirestore.instance.collection('messages').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(
child: Text(snapshot.error.toString()),
);
}
if (snapshot.hasData) {
final messages = snapshot.data!.docs;
List<Text> messageWigdets = [];
for (var message in messages) {
final messageText = message['text'];
final messageSender = message['sender'];
final messageWigdet =
Text('$messageText from $messageSender');
messageWigdets.add(messageWigdet);
}
return Expanded(
child: ListView(
children: [...messageWigdets],
),
);
}
return const CircularProgressIndicator.adaptive();
},
),

Resources