Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load data asynchronously into ChangeNotifier model in Flutter

Tags:

in my Flutter application I have a widget

class HomeScreen extends StatelessWidget

that uses a model

class HomeScreenModel extends ChangeNotifier

These two objects are tied together using a ChangeNotifierProvider.

When the application loads the HomeScreen widget I would like to call a custom init() function of HomeScreenModel to load asynchronously some data from the disk into the model and then notify the listener with notifyListeners() function. This should be done once.

What's the right place to call this init() function? As far as I know, for a stateless widget there are no lifecycle functions called only once. I'm pretty sure, though, that the constructor of HomeScreenModel is called only once.

Is it safe to call the async HomeScreenModel.init() function from its own constructor? Is there any best practice on how to asynchronously load data into a model implemented as a ChangeNotifier?

Thanks to all!

like image 585
DSoldo Avatar asked Aug 29 '19 13:08

DSoldo


1 Answers

After a bit of searching and tests I choose to call the async init function from the HomeScreenModel constructor. So I have

HomeScreenModel(BuildContext context) {
  var initFuture = init(context);
  initFuture.then((voidValue) {
    _log.d('init finished');
    state = HomeScreenModelState.initialized;

    notifyListeners();
  });
}

and the init function prototype is

Future<void> init(BuildContext context) async

I have found that another way to do this is to use a StatefulWidget and call the async init from the

initState()

function. This function is called only once so is like the ChangeNotifier constructor.

As of now I'm not using StatefulWidgets because it seems to me that they create a sort of strong coupling between ui and business logic. So as of now the above solution seems fine to me.

I hope it can help someone

like image 147
DSoldo Avatar answered Oct 19 '22 08:10

DSoldo