I am newbie at Flutter, I want to fetch data once from Firebase but when I use foreach in setState, it gives infinite loop. I tried initState but I couldn't figure it out with Future.
Here is my code:
class _AnasayfaScreenState extends State<AnasayfaScreen> {
final databaseRef = FirebaseDatabase.instance.reference();
ActivityModel activity = ActivityModel();
List<Map<dynamic, dynamic>> lists = [];
}
Future getActivity() async {
return await databaseRef
.child('activities')
.limitToLast(3)
.once()
.then((DataSnapshot dataSnapshot) {
setState(() {
Map<dynamic, dynamic> values = dataSnapshot.value;
lists.clear();
values.forEach((key, values) {
lists.add(values);
});
});
});
}
@override
Widget build(BuildContext context) {
getActivity();
return Scaffold(
appBar: AppBar(
// some stuff
title: Text("Title: " lists[index]["title"] "\nDate: " lists[index]["date"] "\nN: Number of people" lists[index]["maxPeople"] "\nActivity Owner: " lists[index]["ownername"]),
Any help would be awesome for me, thanks.
CodePudding user response:
Here is a very basic example of what you can do:
class _AnasayfaScreenState extends State<AnasayfaScreen> {
final databaseRef = FirebaseDatabase.instance.reference();
ActivityModel activity = ActivityModel();
bool isLoading = true;
List<Map<dynamic, dynamic>> lists = [];
@override
void initState(){
super.initState();
getActivity();
}
Future getActivity() async {
await databaseRef
.child('activities')
.limitToLast(3)
.once()
.then((DataSnapshot dataSnapshot) {
Map<dynamic, dynamic> values = dataSnapshot.value;
lists.clear();
values.forEach((key, values) {
lists.add(values);
});
});
setState(() {
isLoading = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: isLoading ? Container() // Add your widget and work here instead of Container
: CircularProgressIndicator(),
);
}