一尘不染

提供者的状态管理

flutter

我有一个简单的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:

 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

现在我有类似的东西:

@override
  Widget build(BuildContext context) {
    final appState = Provider.of<AppState>(context);
...

这只是登录视图的一个用例,但是我确定可以在其他情况下使用此功能。


阅读 302

收藏
2020-08-13

共1个答案

一尘不染

如果您打算在整个应用程序中使用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视频解释了代码

2020-08-13