如何在创建MaterialApp后调用方法?

问题描述 投票:1回答:2

据我所知,创建一个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'),
            ),
          ],
        ),
      ),
    ),
  );
}
dart flutter
2个回答
1
投票

通常你可以使用FutureBuilderto检查你的方法,我在这里使用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.


0
投票

您可以将Login和Home页面分成两个单独的Widgets,然后在顶级窗口小部件的build方法中有条件地使用它们。

就像是:

@override
build(BuildContext context) {
  return new Container(
    child: isLoggedIn ? HomeWidget : LoginWidget
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.