据我所知,创建一个MaterialApp实例会创建导航器以及其他一些UI功能。当我的应用程序启动时,我想运行一个方法来检查用户是否登录,如果没有显示登录页面。我该怎么做呢?以下是我的main.dart
的开头final scaffoldKey = new GlobalKey<ScaffoldState>();
final formKey = new GlobalKey<FormState>();
String _email;
String _password;
void _submit() {
final form = formKey.currentState;
if (form.validate()) {
form.save();
// Email & password matched our validation rules
// and are saved to _email and _password fields.
_performLogin();
}
}
void _performLogin() {
// This is just a demo, so no actual login here.
final snackbar = new SnackBar(
content: new Text('Email: $_email, password: $_password'),
);
scaffoldKey.currentState.showSnackBar(snackbar);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
key: scaffoldKey,
appBar: new AppBar(
title: new Text('Validating forms'),
),
body: new Padding(
padding: const EdgeInsets.all(16.0),
child: new Form(
key: formKey,
child: new Column(
children: [
new TextFormField(
decoration: new InputDecoration(labelText: 'Email'),
validator: (val) =>
!val.contains('@') ? 'Not a valid email.' : null,
onSaved: (val) => _email = val,
),
new TextFormField(
decoration: new InputDecoration(labelText: 'Password'),
validator: (val) =>
val.length < 6 ? 'Password too short.' : null,
onSaved: (val) => _password = val,
obscureText: true,
),
new RaisedButton(
onPressed: _submit,
child: new Text('Login'),
),
],
),
),
),
);
}
答案 0 :(得分:1)
通常,您可以使用FutureBuilder
检查您的方法,我在这里使用FirebaseAuth
:
return new FutureBuilder(future: FirebaseAuth.instance.currentUser(),
builder: (BuildContext context, AsyncSnapshot<FirebaseUser> user) {
///Check if user data != null
return user.hasData? new HomeScreen(....):new LoginScreen(...)
......
您还可以检查flutter archtiecture pattern以更好的方式管理用户身份验证状态。
Also here is a useful example on how to manage Firebase with Redux library.
答案 1 :(得分:0)
您可以将登录页面和主页面分成两个单独的窗口小部件,然后在顶级窗口小部件的build
方法中有条件地使用它们。
类似的东西:
@override
build(BuildContext context) {
return new Container(
child: isLoggedIn ? HomeWidget : LoginWidget
)
}