Flutter - 在热重载时丢失提供者状态

Flutter - losing Provider state on hot reload

当我热重载我的应用程序时,我丢失了来自我的提供商的状态 类。我知道 Provider 正确地保留了状态,所以我知道问题出在我的代码中,但我无法弄清楚我哪里出错了。我有以下内容:


main.dart

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: GlobalData.fetchTheme(),
      builder: (BuildContext context, AsyncSnapshot<String> themeSnapshot) {
        if (themeSnapshot.hasData) {
          GlobalData.theme = themeSnapshot.data;
          return Phoenix(
            child: MaterialApp(
              title: 'MyApp',
              home: Scaffold(body: Root()),
              theme: ThemeData(
                accentColor: Palette.green
              ),
            )
          );
        }
        return Loading();
      }
    );
  }
}

root.dart

class Root extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<FirebaseUser>(
      stream: FireAuth().getInstance().onAuthStateChanged,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.active) {
          FirebaseUser user = snapshot.data;
          if (user != null) {
            GlobalData.setUid(user.uid);
          }
          return user == null ? Auth() : SafeArea(child: KeyboardDismisser(child: Core()));
        } else {
          return Loading();
        }
      },
    );
  }
}

core.dart

class Core extends StatelessWidget {
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        FutureBuilder(
          future: Users.getUser(GlobalData.uid),
          builder: (BuildContext context, AsyncSnapshot<TuneUser> userSnapshot) {
            if (userSnapshot.hasData) {
              return MultiProvider(
                providers: [
                  ChangeNotifierProvider(create: (context) => UserProvider(userSnapshot.data)),
                  ChangeNotifierProvider(create: (context) => SearchProvider()),
                  ChangeNotifierProvider(create: (context) => DetailsProvider()),
                ],
                child: Expanded(child: BottomBarNavigation())
              );
            }
            return Expanded(child: Loading());
          }
        ),
        BottomBar()
      ]
    );
  }
}

我假设在某些时候我正在重建或失去状态,而我不应该,我已经在类似问题的帮助下尝试了很多事情,但我似乎无法修复它。

有什么想法吗? 非常感谢您的帮助。

干杯,

安迪

把你MultiProvider包裹在main.dart

MultiProvider(
  providers: [
    ChangeNotifierProvider(create: (context) => UserProvider(userSnapshot.data)),
    ChangeNotifierProvider(create: (context) => SearchProvider()),
    ChangeNotifierProvider(create: (context) => DetailsProvider()),
  ],
  child: child: MaterialApp(
    title: 'MyApp',
    home: Scaffold(body: Root()),
    theme: ThemeData(
      accentColor: Palette.green
    ),
  ),
),