Reputation: 93
I want to fetch data from firestore and use that to build cards in Flutter using ListView on the homepage. While using the navigation menu to switch between screens, I intend to reuse the data once fetched in a session rather than fetching it from the database every time I return to the homepage. But, this is not happening; The data is fetched from the database every time I go to the homepage.
FutureBuilder(
future: databaseService(),
builder: (context, snapshot) {
if (snapshot.hasData) {
stringMap = snapshot.data;
}
return ListView.builder(
itemBuilder: (context, index) {
stringMap.forEach((index, value) => {
print("The stringMap is ${stringMap.keys.toList()}"),
});
return HomepageCards(
user: widget.user,
cardDetails: stringMap[stringMap.keys.toList()[index]],
);
},
itemCount: stringMap.length,
scrollDirection: Axis.vertical,
controller: _controller,
shrinkWrap: true,
);
},
)
databaseService() async {
return DatabaseService().streamHomePage(widget.user);
}
DatabaseService.dart
class DatabaseService {
final Firestore _db = Firestore.instance;
HomePage home = new HomePage();
Map homePageMap = new Map<String, Map<String, dynamic>>();
/// Query a subcollection
Future streamHomePage(FirebaseUser user) async {
// Initialise the model map
home.homeModel = <String, dynamic>{};
home.homeModel['driverDetails'] = new Map();
var ref = _db
.collection('homepage')
.document(user.uid)
.collection('h')
.document('28032020');
// TODO: Try to use cached data. Also try to find the pattern for switching between server and cache
await ref.get(source: Source.serverAndCache).then((ref) => {
ref.data.forEach((index, value) => {
home.homeModel = value,
homePageMap[index] = value,
}),
});
return homePageMap;
}
}
Any leads to make the data once fetched reusable would be highly appreciated.
Upvotes: 1
Views: 561
Reputation: 80914
Since you only want to fetch it once and then fetch it from the session, therefore you can just check if the session contains the data or not. Another way is to use shared_preferences
, for example:
SharedPreferences prefs = await SharedPreferences.getInstance();
databaseService() async {
await prefs.setBool('retrieved', true);
return DatabaseService().streamHomePage(widget.user);
}
Then before executing the FutureBuilder
check if retrieved is equal to true using getBool()
and retrieve data from the session
Upvotes: 1