我正在使用Provider来管理我的应用程序的状态.以下是我是如何实现它的.

hypnose.dart

class _HypnoseAppState extends State<HypnoseApp> {
  @override
  Widget build(BuildContext context) {
    UserService userService = UserService();
    AudioUtilService audioUtilService = AudioUtilService();

    return MultiProvider(
      providers: [
        ChangeNotifierProvider<UserService>.value(
          value: userService,
        ),
        ChangeNotifierProvider<AudioUtilService>.value(
          value: audioUtilService,
        )
      ],
      child: MaterialApp(
          debugShowCheckedModeBanner: false,
          title: Globals.title,
          theme: ThemeData(primarySwatch: Colors.cyan),
          darkTheme: ThemeData.dark(),
          initialRoute: '/',
          routes: {
            '/': (BuildContext context) => WelcomeScreen(userService),
            '/home': (BuildContext context) => HomePageSwitcher(),
            '/audiocreate': (BuildContext context) => AudioCreateScreen()
          }),
    );
  }
}

home_switcher.dart

class HomePageSwitcher extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<UserService>(
      builder: (BuildContext context, UserService userService, Widget child) {
        return Scaffold(
            appBar: AppBar(),
            drawer: Drawer(
              child: Column(
                children: <Widget>[
                  UserAccountsDrawerHeader(
                    accountEmail: Text(userService.loggedInUser.email),
                    accountName: Text(userService.loggedInUser.name),
                    currentAccountPicture:
                        Image.network(userService.loggedInUser.avatar),
                  )
                ],
              ),
            ),
            body: Center(
              child: RaisedButton(
                child: Text('Sign out'),
                onPressed: () async {
                  await userService.signOut();
                  Navigator.pushNamed(context, '/');
                },
              ),
            ));
      },
    );
  }
}

user_service.dart

class UserService extends ChangeNotifier {
  // Get auth instances
  final GoogleSignIn _googleSignIn = GoogleSignIn();
  final FirebaseAuth _auth = FirebaseAuth.instance;

  // Store reference of user collection
  final CollectionReference userDb = Firestore.instance.collection('user');

  // Master instance of logged in user
  User _loggedInUser;

  // Getter to access loggedInUser
  User get loggedInUser {
    return _loggedInUser;
  }

  PublishSubject<AuthState> _authStateSubject = PublishSubject();

.... other code

现在的问题是,每次我在主页上热重新加载时,我开始得到NoSuchMethodError,因为它说邮箱、名称等属性被调用为null,我认为这意味着状态丢失.我怎样才能克服同样的问题?我做错什么了吗?

推荐答案

你不应该使用ChangeNotifierProvider.value.请改用默认构造函数:

ChangeNotifierProvider(
  builder: (_) => UserService(),
)

否则,您的构建方法是不纯的,并且会出现如How to deal with unwanted widget build?中所述的问题

Dart相关问答推荐

如何找到这个Currate函数的返回类型?

Dartpad使用基本身份验证发出请求

flutter.io (dart) - 将填充设置为设备宽度的百分比?

停止在缓存中保存 Flutter Web Firebase 托管

AppLifcycleState.didChangeLifecycleState( ) 函数在应用程序进入前台或后台时不被调用

使用 dart 中的括号表示法访问对象的属性

Flutter - 可以在没有 Firebase 的情况下使用 Google 登录吗?

Flutter:Firebase FieldValue.serverTimestamp() 到 DateTime 对象

如何计算列表中元素的出现次数

dart:web_gl: 渲染警告:texture bound to texture unit 0 is not renderable

在dart中使用动态(可变)字符串作为正则表达式模式

如何在dart中的多个文件中编写多个单元测试?

如何更改手机屏幕上的Flutter应用程序名称显示?

如何用dart语言初始化超类变量?

Dart:打印整数和字符串

安装 dart-sdk 后找不到 pub 命令

pub 依赖和 dev_dependencies 有什么区别?

Dart 中 == 和 === 有什么区别?

导出两个具有相同类名的库

Dart 中的函数类型定义(typedefs)/函数类型别名(function-type aliases)是什么?