0

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

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

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

但是,在颤振热重启或打开/关闭应用程序后,会显示介绍屏幕,而不是登录屏幕。在 Intro Screen 中单击 onPressed 后,现在设置为 Sign In 屏幕的不应该state在重新启动之间持续存在并导致 Intro Screen 被跳过并显示 Sign In 屏幕吗?

正如您在下面看到的,main.dart有一个初始 AppRoutes。路由。在app_router.dart,这个“根”屏幕打开root_screen.dart,它是ConsumerWidgetwatch的 StateNotifierProvider,在 中称为“accountSetupProvider” account_setup_provider.dart

主要.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();
});
4

1 回答 1

1

甚至不看你的代码,只看你的主题行,这对我来说一点也不奇怪。“热重启”重置所有变量。怎么可能保存任何状态?您是否正在寻找“热重载”?

于 2021-02-17T01:07:54.410 回答