Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

flutter - Run a method before the widget build complete?

I would like to know if there is any way to call a function on only the starting of the app, but before building the widget. I would like to fetch data from the JSON only on starting of the app. But the Method is in the provider and needs context.

I tried several ways but nothing is perfect. I called the function on initState of the HomeScreen() but still need to refresh the app to see. (because the method is called after the layout is built.. so no items loaded)

void initState() {
super.initState();

Provider.of<Utils>(context, listen: false)
    .fetchDataFromJSON()
    .then((value) {
  setState(() {});
});

Still need refresh or change page to load the items. I am doing this initState in tabScreen.dart. Obviously, the data needed for creating the Elements on HomeScreen but its not loading at first time.

EDIT: I got it fixed by changing the place of calling the function. My Mistake is I called the init state from the TabScreen's InitState. I changed it to HomeScreen's InitState and it worked fine. Hope my mistake will help someone else.

question from:https://stackoverflow.com/questions/66049890/run-a-method-before-the-widget-build-complete

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Method 1 (not sure) You can use your method in main method then run the app.

But I do not now if this causes lateInit error.

void main() {
   someFunction.then((value) {
      runApp(MyApp);
    })
}

Method 2

create boolean variable like loaded set this to false

and then use ternary operator where you assign your widget needs the data.

if loaded is false then load another widget not widget that needs data

use your function in initState when you functions completes set loaded to true


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...