首页 > 解决方案 > 应用程序被杀死后,Flutter firebase auth 不会持续存在

问题描述

我正在尝试通过使用文档中的此代码将 firebase 身份验证状态保持在颤振应用程序中,但是当我在模拟器中杀死该应用程序并再次打开它时,它无法识别用户。我可以使用 sharedpreferences 但我只想使用 firebase,我在这里做错了什么?

主要.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // Create the initialization Future outside of `build`:
  final Future<FirebaseApp> _initialization = Firebase.initializeApp();
  final FirebaseAuth auth = FirebaseAuth.instance;

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      // Initialize FlutterFire:
      future: _initialization,
      builder: (context, snapshot) {
        // Check for errors
        if (snapshot.hasError) {
          return (MaterialApp(
            home: Warning(
              warning: 'Error',
            ),
          ));
        }
        // once complete show your app
        if (snapshot.connectionState == ConnectionState.done) {
          print('CONNECTED');

          if (AuthService().user() == null) {
            return MaterialApp(
              home: LoginPage(),
            );
          } else {
            return MaterialApp(
              home: HomePage(),
            );
          }
        }
        // if nothing happens return loading
        return MaterialApp(
          home: //LoginPage()
              Warning(
            warning: 'Loading',
          ),
        );
      },
    );
  }
}

AuthService 类

导入“包:firebase_auth/firebase_auth.dart”;

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  // auth change user stream
  User user() {
    // ignore: deprecated_member_use
    _auth.authStateChanges().listen((User user) {
      if (user == null) {
        return null;
      } else {
        return user;
      }
    });
  }
}

我希望你能帮助我理解问题并解决它,谢谢。

标签: firebaseflutterfirebase-authentication

解决方案


由于authStateChanges返回 a Stream,因此您也需要StreamBuilder在代码中使用 a 来包装该异步操作。

像这样的东西:

// once complete show your app
if (snapshot.connectionState == ConnectionState.done) {
  print('CONNECTED');
  return StreamBuilder(
    stream: FirebaseAuth.instance. authStateChanges(),
    builder: (BuildContext context, snapshot) {
      if (snapshot.hasData) {
        return MaterialApp(
          home: LoginPage(),
        );
      } else {
        return MaterialApp(
          home: HomePage(),
        );
      }
    }
  )
}

不相关:您重复代码以MaterialApp非常频繁地创建一个,这不是必需的。例如,在上面的代码片段中,我们可以只提及一次MaterialApp并得到相同的结果:

// once complete show your app
if (snapshot.connectionState == ConnectionState.done) {
  print('CONNECTED');
  return StreamBuilder(
    stream: FirebaseAuth.instance. authStateChanges(),
    builder: (BuildContext context, snapshot) {
      return MaterialApp(
        home: snapshot.hasData && snapshot.data != null ? HomePage() : LoginPage(),
      )
    }
  )
}

如果您对所有提及MaterialApp和其他重复执行此操作,则可以显着减少代码,使其不易出错且更易于维护。


推荐阅读