我有一个简单的Provider类:
import 'package:flutter/foundation.dart'; class AppState with ChangeNotifier { bool _isLoggedIn = false; bool get isLoggedIn => _isLoggedIn; set isLoggedIn(bool newValue) { _isLoggedIn = newValue; notifyListeners(); } }
在登录类中isLoggedIn,如果登录成功,则将其设置为true:
isLoggedIn
void _signInWithEmailAndPassword(appState) async { try { final FirebaseUser user = await _auth.signInWithEmailAndPassword( ... ); if (user != null) { appState.isLoggedIn = true; appState.userData = user.providerData; ... } } catch (e) { setState(() { _errorMessage = e.message; }); } }
即使成功登录后,按Android上的“后退”按钮也可以使用户返回此页面。因此,我想知道是否Provider.of可以以前访问过Widget build,如果isLoggedIn是则可以重定向用户true。
Provider.of
Widget build
true
现在我有类似的东西:
@override Widget build(BuildContext context) { final appState = Provider.of<AppState>(context); ...
这只是登录视图的一个用例,但是我确定可以在其他情况下使用此功能。
如果您打算在整个应用程序中使用FirebaseUser或“登录用户”,我建议您在应用程序的最高级别上添加提供程序。例
void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { MyApp(); @override Widget build(BuildContext context) { return MultiProvider( providers: [ StreamProvider<FirebaseUser>.value( stream: FirebaseAuth.instance.onAuthStateChanged, // Provider here ), ], child: MaterialApp( title: 'My App', debugShowCheckedModeBanner: false, theme: ThemeData( primaryColor: Colors.green, primarySwatch: Colors.green, accentColor: Colors.yellow, ), home: MainPage(), ), ); } } class MainPage extends StatefulWidget { MainPage({Key key, this.storage}) : super(key: key); final FirebaseStorage storage; @override _MainPageState createState() => _MainPageState(); } class _MainPageState extends State<MainPage> with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { final user = Provider.of<FirebaseUser>(context); // gets the firebase user bool loggedIn = user != null; return loggedIn ? HomePage() : LoginPage(); // Will check if the user is logged in. And will change anywhere in the app if the user logs in } }
参考资料
Fireship 185提供者
很棒的YouTube视频解释了代码