简体   繁体   English

Flutter/FirebaseAuth:如何在应用启动时自动登录用户?

[英]Flutter/FirebaseAuth : How can I autologin a user at app launch?

I have the following methods to see if the user is already logged in, which in this case I did log in and the getCurrentUser() function works because in the console it does return "USER IS NOT NULL" but the home widget is still null giving me the "EXCEPTION CAUGHT BY WIDGETS LIBRARY" saying that the home can't be null and stuff.我有以下方法来查看用户是否已经登录,在这种情况下我确实登录了并且getCurrentUser()函数有效,因为在控制台中它确实返回“USER IS NOT NULL”但主页小部件仍然为空给我“小部件库的异常捕获”,说家不能为空之类的东西。

userAPI.dart用户API.dart

Future<FirebaseUser> getCurrentUser() async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();

if (user != null) {
  return user;
} else {
  return null;
}
}

main.dart main.dart

class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
Widget home;

APIs().usersAPI.getCurrentUser().then((u) {
  if (u == null) {
    print('USER IS NULL');
    home = WelcomePage();
  } else {
    print('USER IS NOT NULL');
    home = FeedPage();
  }
});

return MaterialApp(
  title: "Jedi",
  debugShowCheckedModeBanner: false,
  home: home,
  routes: {
    '/login' : (context) => new LoginPage(),
    '/feed' : (context) => new FeedPage(),
  },
);
}
}

You need to make the App a StatefulWidget and call setState when setting the home page需要将 App 设为StatefulWidget并在设置主页时调用setState

setState(() {
   home = WelcomePage();
});

setState(() {
   home = FeedPage();
});

Plus you may need to set the home page to something other than null before the API returns.另外,您可能需要在 API 返回之前将主页设置为 null 以外的值。

What probably would be a better pattern is to use a FutureBuilder .使用FutureBuilder可能是更好的模式。 This way you will be returning the correct Widget depending on the state you are in.这样,您将根据您所处的状态返回正确的 Widget。

return MaterialApp(
  title: "Jedi",
  debugShowCheckedModeBanner: false,
  home: FutureBuilder<FirebaseUser>(
     future: APIs().usersAPI.getCurrentUser(),
     builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {

        switch (snapshot.connectionState) {
            case ConnectionState.none:
            case ConnectionState.waiting: 
               return CircularProgressIndicator();
            default: 
               if (snapshot.hasError)
                  return Text('Error: ${snapshot.error}');
               else
                 if(snapshot.data == null)
                    return WelcomePage();
                 else 
                    return FeedPage();
        }

     }
  ),
  routes: {
    '/login' : (context) => new LoginPage(),
    '/feed' : (context) => new FeedPage(),
  },
);
}

Advancing the answer given by @aqwert, you need to check for the user is not null/is null after the connection status.推进@aqwert 给出的答案,您需要在连接状态之后检查用户是否为空/是否为空。 See below working example - this assumes autologin if user is not null.请参阅下面的工作示例 - 如果用户不为空,则假定自动登录。

class LandingPage extends StatelessWidget {//call this class from the main.dart
 @override
 Widget build(BuildContext context) {
  return StreamBuilder<FirebaseUser>(
  stream: FirebaseAuth.instance.onAuthStateChanged,
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.active) {
      FirebaseUser user = snapshot.data;//get the user status once the connection is established
      if (user == null) {
        //print("User is NULL::: " + user.toString());
        return LoginScreen();//
      }
      print("User is NOT NULL::: " + user.toString());
      return DefaultScreen();//home screen
    } else {
      return Scaffold(
        body: Center(
          child: CircularProgressIndicator(),//called in case all fails while waiting for connection status
        ),
      );
    }
  },
);

Here is my simple solution you can try this, First we need a stateful widget and override the function initState() inside initState() we can work something look like this-这是我的简单解决方案,你可以试试这个,首先我们需要一个有状态的小部件并覆盖 initState() 中的函数 initState() 我们可以像这样工作 -

class _MyAppState extends State<MyApp> {
  String initPage;
  final FirebaseAuth auth=FirebaseAuth.instance;
  User currentUser;

  @override
  void initState() {
    super.initState();
    try {
      currentUser = auth.currentUser;
      if(currentUser!=null){
        initPage=Chat.id;
 /*
      here id is static variable which declare as a page name.
       */
      }
      else{
        initPage=Home.id;
      }
    }
    catch(e){
      print(e);
      initPage=Home.id;
    }

  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
 

      initialRoute: initPage,
      routes: {
        Home.id: (context) => Home(),
        Login.id: (context) => Login(),
        Registration.id: (context) => Registration(),
        Chat.id: (context) => Chat(),
      },
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter FirebaseAuth:我如何检查用户是否在无效中登录? - Flutter FirebaseAuth: How can i check if a User is LoggedIn in a void? 我可以使用 sharedPreference 代替 FirebaseAuth.instance.currentUser.email Flutter 来获取当前用户数据吗 - can I use sharedPreference to get current user data instead of FirebaseAuth.instance.currentUser.email Flutter 我应该如何在我的 Flutter 应用程序中使用 FirebaseAuth.instance.onAuthStateChanged? - How am I supposed to use FirebaseAuth.instance.onAuthStateChanged in my flutter app? 如何在Flutter中从FirebaseAuth电话验证方法返回变量? - How can I return variable from FirebaseAuth phone verification method in flutter? 如何获取当前用户的电子邮件地址 FirebaseAuth/Flutter - How to get current user email address FirebaseAuth/Flutter FirebaseAuth - 我如何等待价值 - FirebaseAuth - how can I wait for value Flutter:如何使用 FirebaseAuth idTokenChange? - Flutter: How to use FirebaseAuth idTokenChange? 如何解决匿名用户的 FirebaseAuth isAnonymous 返回 false? - How do I solve FirebaseAuth isAnonymous return false on an Anonymous user? 我如何在我的 flutter 应用程序中使用第二个 firebase 项目? - How can i user second firebase project in my flutter app? 在 Flutter 中使用 FirebaseAuth 检查用户的身份验证状态 - check authentication state of User using FirebaseAuth in Flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM