in my app I want to load events from the database. My problem is: If the user does not have any events stored, the "getAll"-Function i created (to add events from my database) is called non-stop. How can I make a better implementation?
Abstract from my provider:
class EventProvider extends ChangeNotifier {
List<Events> _events = [];
List<Events> get events => _events;
getAllEvents() async {
Datenbank DBprovider = Datenbank();
final data = await Datenbank.getAllTermine();
for (var i = 0; i < data.length; i ) {
_events.add(data[i]);
}
notifyListeners();
}
My app code:
@override
Widget build(BuildContext context) {
final provider = Provider.of<EventProvider>(context, listen: true);
events = Provider.of<EventProvider>(context).events;
//I created this "if" in order to load the event-List for the first time
//and get all items (i guess, that this is total ineffcient)
//also, if there are no events this function is called endlessly and rebuilds
//everything on and on and on....
if (events.isEmpty) {
provider.getAllEvents();
}
thanks for help!
CodePudding user response:
You can call method once widget is created. Make your widget StatefulWidget
@override
void initState() {
super.initState();
final provider = Provider.of<EventProvider>(context, listen: false);
provider.getAllEvents();
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<EventProvider>(context, listen: true);
...
}