firebase - 应用程序被杀死后,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;
}
});
}
}
我希望你能帮助我理解问题并解决它,谢谢。
解决方案
由于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
和其他重复执行此操作,则可以显着减少代码,使其不易出错且更易于维护。
推荐阅读
- android - 为什么我的共享库中存在展开符号
- iis - 在 IIS 上运行的 C# 服务器上使用 HTTPS 的 AWS 问题
- microcontroller - 中断内的静态变量
- c# - 为什么我的 Unity 的 C# 相机控制器脚本只能在两个相机之间切换,而不是切换回来?
- filter - 使用一个过滤器在多个视图中过滤多个月视图
- c - C 的 Eclipse 开发:调试器问题 - 无法执行 MI 命令
- go - 如何在函数调用链中使用 context.Context 取消
- flutter - Flutter 应用程序错误 - 类型“时间戳”不是“日期时间”类型的子类型
- java - 获取 Int 的最后三位
- c# - 许多不同的类对象监听一个事件c#