How to use providers to load data before consuming

1.3k views Asked by At

In my application I use provider in the following manner;

I create the schedule view like this;

await Navigator.of(context, rootNavigator: true).push(
                    MaterialPageRoute(
                      builder: (BuildContext context) =>
                          ScheduleView.create(context, experience),
                    ),
                  );

The create function;

    static Widget create(BuildContext context, ExperienceDetailed experience) {
final db = Provider.of<Database>(context, listen: false);
// to get initial data i need to call function
// db.getSchedules();
// can i just do it here ?
return ChangeNotifierProvider<ScheduleViewModel>(
  create: (context) => ScheduleViewModel(db, experience),
  child: Consumer<ScheduleViewModel>(
    builder: (context, model, _) => ScheduleView(
      experience: experience,
      model: model,
    ),
  ),
);

} Before loading ScheduleView I also want to load the initial set of data that is displayed in the ScheduleView.

The loading function is inside the model called "getSchedule()"

At the moment I use initState in the "ScheduleView " to call this function and load the initial data.

Is there a way to load the data before calling the builder. I have seen option called MultiProvider and ChangeNotifierProxyProvider.

Can they be used here ?

1

There are 1 answers

5
yellowgray On

I make a quick guess: Is ChangeNotifierProvider.value works for you? You can create ScheduleViewModel as a Object first, pass into provider as a value and use it below.

I think you might want a futureBuilder which can choose to show other widget when asynchronous data is not ready yet.

return FutureBuilder(
  future: db.getSchedules(), // it should be a async future function
    builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
      if(snapshot.connectionState == ConnectionState.done && snapshot.hasData){
        return ... // when data is done you can get the data by snapshot.data
      }else{
        return CircularProgressIndicator(); // waiting widget
      }
    };

);

You can see more detail here FutureBuilder