How can I call an async method in StatelessWidget.build method?
I have below code in flutter. In initialRoute:
attribute, it needs to call isLoggedIn()
method which is an async function. I got an error saying I need to call await
in a async
function. But the build
method is overridden from its parent class which is not async
method. How can I call an await
inside an overridden method?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class MyApp extends StatelessWidget { / / This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: '', theme: ThemeData( primarySwatch: Colors.blue, ), initialRoute: await isLoggedIn() ? '/' : '/login' , routes: <String, WidgetBuilder>{ '/' : (BuildContext context) { return MyHomePage(title: 'Home Page' ); }, '/login' : (BuildContext context) { return Login(); }, } ); } } |
answer 1;
According to me it is impossible to do what you are trying to do.
As you mention isLoggedIn is async which is gonna take time to calculate, meanwhile build method complete build. You can use futureBuilder to do async task in Stateless widget but as this is your initial route, you have to provide it, so again it will not work.
I recommend you to add splash screen, where you can calculate mean call that method and find out navigation.
answer 2;
I would suggest it would be a better option to create an authentication router widget to handle the logged in status of the app that way if the user logs out of the app the navigation can change automatically. i.e:
initialRoute: '/user-auth'
Then is a UserAuth widget you can run your logged in logic.
answer 3;, ---ok
When I had this problem, I solved it by putting the await not inside MyApp.build, but in the MyApp call in main. Like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | Future <Widget> selectStartPage () async { return await isLoggedIn() ? HomePage (): Login (), } Future<void> main() async { / / whatever setup you need... runApp (MyApp (await selectStartPage())); } class MyApp extends StatelessWidget { final Widget startPage; MyApp (this.startPage); @override Widget build (BuildContext context){ return MaterialApp( title: '', theme: ThemeData( primarySwatch: Colors.blue, ), initialRoute: startPage, ); } } |
Futurebuilder in statelesswidget.............
Getx onInit..
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】