Reputation: 1027
I am using cloud firestore as a backend and the provider package for state management for my app. I have a BooksProvider class (ChangeNotifierProvider) which I use to fetch, add, update and delete data. In this class, I have an async method to fetch data from cloud firestore.
Future<void> fetchAndSetData() async {
try {
final response = await bookCollection.getDocuments();
List<Book> loadedBooks = [];
final querySnapshot = response.documents;
if (querySnapshot.isEmpty) {
return;
}
querySnapshot.forEach((book) {
loadedBooks.add(
Book(
id: book.documentID,
title: book.data['title'],
description: book.data['description'],
image: book.data['image'],
rate: book.data['rate'],
category: CategoryName.values[book.data['category_index']],
date: book.data['date'],
price: book.data['price'],
isFree: book.data['isFree'],
isFavorite: book.data['isFavorite']),
);
});
_booksList = loadedBooks;
notifyListeners();
} catch (e) {
throw e;
}
}
I am trying to use it with the future builder but it doesn't work as it is always stuck in ConnectionState.waiting case.
class BooksScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
// final booksData = Provider.of<BooksProvider>(context);
// final books = booksData.booksList;
// final _noContent = Center(child: Text('No books are available.'));
return FutureBuilder(
future: Provider.of<BooksProvider>(context).fetchAndSetData(),
builder: (ctx, dataSnapshot) {
switch (dataSnapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.active:
return Text('waiting'); //always returning waiting
break;
case ConnectionState.done:
return Text('done');
break;
case ConnectionState.none:
return Text('none');
break;
default:
return Text('default');
}
},
);
}
}
I don't know what might be wrong, I tried to change the return type of the async method so that it returns a list of Book but it didn't work. I also used if statement instead of the switch case and the same thing kept happening.
In addition, I tried it with if (dataSnapshot.hasdata) as it is suggested by on of the answers, and it worked!, but i want to use a spinner while waiting and when i tried it, the same problem occurred again.
I tried the same method with another approach where i used stateful widget and didChangeDependencies() method to fetch the data and it worked just fine, and I am trying future builder approach because I don't know how to handle errors with didChangeDependencies() approach.
so if you please can help me with the future builder or error handling with the latter approach. Thank you in advance.
Upvotes: 0
Views: 2109