我是 Flutter 和 Dart 的新手。所以我试图在 Flutter 中构建一个简单的身份验证系统。当用户打开应用程序时,我想向他们显示LoginScreen(他们之前未登录的位置)或HomeScreen登录时间。
loadWidget,它返回一个Future将确定是否存在持久数据,从而获取用户的信息并显示主屏幕。child 属性不允许我为其分配 Future,我不确定但我想我必须为此使用 FutureBuilder 小部件?
第一次尝试
Future<Widget> loadWidget() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
// already logged in
String phone = prefs.getString('phoneNumber');
if (phone != null) {
helper.user = await checkUser(phone); // fetch user info
return HomeScreen();
}
// Not logged in
else {
return Login();
}
}
Run Code Online (Sandbox Code Playgroud)
对于构建功能,这不起作用
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: loadWidget(), // This does not allow me to assign a future
)
);
}
Run Code Online (Sandbox Code Playgroud)
第二次尝试:使用 FutureBuilder
我在这里阅读了有关 Futurebuilder 的信息如何将 future<> 分配给颤动中的小部件?它看起来像要走的路,所以我修改了我的构建方法
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: FutureBuilder(
future: loadWidget(),
builder: (BuildContext context, AsyncSnapshot<Widget> widget){
return widget;
},
),
),
);
}
Run Code Online (Sandbox Code Playgroud)
但这给了我以下错误:
返回类型“AsyncSnapshot”不是匿名闭包定义的“Widget”。
我怎样才能做到这一点?谢谢!
You are doing it right but the problem is with the returning object from the FutureBuilder, see the comments in this code:
// *NOTE: build return Widget: Widget build...
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: FutureBuilder(
future: loadWidget(),
builder: (BuildContext context, AsyncSnapshot<Widget> widget){
// But 'widget' here is NOT a widget, it is an AsyncSnapshot object,
// return widget; // **is wrong**
// instead:
return widget.data;
// and better to make it like this:
//if (!widget.hasData) {
// return Center(
// child: CircularProgressIndicator(),
// );
//}
//return widget.data;
},
),
),
);
}
Run Code Online (Sandbox Code Playgroud)
that was to fix the error. An extra advice for cleaner code, keep your Authentication layer(loadWidget) clean by making it return only state(Auth or Not), then catch the state using widget.data inside the FutureBuilder, and then route based on the Auth-state from inside the FutureBuilder.
| 归档时间: |
|
| 查看次数: |
2827 次 |
| 最近记录: |