StateNotifierProvider 不在应用重启之间保持状态

StateNotifierProvider not keeping state between app restarts

使用 flutter_riverpod: ^0.12.4 并在 android 模拟器和物理设备上进行测试。

我做错了什么,登录屏幕 state 值在应用程序重启后没有保留在 StateNotifierProvider 中?

accountSetupProvider 的 state 默认为介绍屏幕。单击介绍屏幕的 onPressed 按钮后,state 更新为登录屏幕,并正确触发重建以显示登录屏幕。

但是,在 flutter 热重启或 opening/closing 应用程序之后,将显示介绍屏幕,而不是登录屏幕。 state,现在在介绍屏幕中单击 onPressed 后设置为登录屏幕,难道不应该在重新启动之间持续存在并导致跳过介绍屏幕并显示登录屏幕吗?

如下所示,main.dart 有一个初始 AppRoutes.root 路由。在 app_router.dart 中,此“根”屏幕打开 root_screen.dart,这是一个 ConsumerWidget,即 watch(ing) 我在 account_setup_provider.dart 中称为“accountSetupProvider”的 StateNotifierProvider。

main.dart

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  runApp(
    ProviderScope(
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: AppRoutes.root,
      onGenerateRoute: (settings) => AppRouter.onGenerateRoute(settings),
    );
  }
}

app_router.dart

class AppRoutes {
  static const String root = RootScreen.id;
  static const String intro = IntroScreen.id;
  static const String signIn = SignInScreen.id;
}

class AppRouter {
  static Route<dynamic> onGenerateRoute(RouteSettings settings) {
    final _args = settings.arguments;

    switch (settings.name) {
      case AppRoutes.root:
        return MaterialPageRoute<dynamic>(
          builder: (_) => RootScreen(),
          settings: settings,
        );
      case AppRoutes.intro:
        return MaterialPageRoute<dynamic>(
          builder: (_) => IntroScreen(),
          settings: settings,
        );
      case AppRoutes.signIn:
        return MaterialPageRoute<dynamic>(
          builder: (_) => SignInScreen(),
          settings: settings,
        );
    }
  }
}

root_screen.dart

class RootScreen extends ConsumerWidget {
  const RootScreen({Key key}) : super(key: key);
  static const String id = 'root_screen';

  @override
  Widget build(BuildContext context, ScopedReader watch) {
    final screen = watch(accountSetupProvider.state);

    if (screen == AppRoutes.signIn) {
      return SignInScreen();
    } else if (screen == AppRoutes.intro) {
      return IntroScreen();
    }
  }
}

intro_screen.dart(仅包括介绍屏幕的 onPressed 部分,我希望将状态设置为新屏幕,即使在颤振热重启或应用重启。)

onPressed: () {
  context
    .read(accountSetupProvider) // see accountSetupProvider StateNotifierProvider below.
    .setScreen(AppRoutes.signIn);
},

account_setup_provider.dart(初始化到 AppRoutes.intro 屏幕。)

class AccountSetupNotifier extends StateNotifier<String> {
  AccountSetupNotifier() : super(AppRoutes.intro);

  void setScreen(String screen) {
    state = screen;
  }
}

final accountSetupProvider = StateNotifierProvider<AccountSetupNotifier>((ref) {
  return AccountSetupNotifier();
});

即使不看你的代码,只看你的主题行,我也不会感到惊讶。 “热重启”重置所有变量。怎么可能有任何状态保存下来?您是在寻找“热重载”吗?