Uwe.Schneider
Uwe.Schneider

Reputation: 1415

flutter : run provider function to load data before/while widget is loading the layout

Structure of code: I have a function, that on a Button click returns a stateful widget A. In a separate file, I have a ChangeNotifier class B, which A needs (it needs the decoded json file) and I use the ChangeNotifier class as a general memory container which all the different widgets have access to.

B:
class Database_Controller extends ChangeNotifier {
  Future<void> _readVeryLargeJsonFrame() async {
    final String response =
    await rootBundle.loadString('assets/tables/largejson.json');
    final data = await json.decode(response);
    return data;
  }
  Other functions to give back entries of data
}

Problem: I would like to execute _readVeryLargeJsonFrame as soon as A is called (potentially with a loading spinner for the user) and before A is loaded (or at least in parallel).

  1. How do I call the ChangeNotifier function in the "init" part of a stateful widget? Peter Koltai mentioned the initState method. But how do I call the ChangeNotifier function from this?

(2. Context problem: So far, I would be using Provider.of<Database_Controller>(context,listen: false)._readVeryLargeJsonFrame(); but how do I get the context argument here?)

(3. Is the Future<void> ... async nature of the _readVeryLargeJsonFrame function a problem here?)

Upvotes: 0

Views: 1040

Answers (1)

cloudpham93
cloudpham93

Reputation: 566

void initState() {
    super.initState();
    WidgetsBinding.instance
        .addPostFrameCallback((_) => yourFunction(context));
  }

Upvotes: 1

Related Questions