使用Hive和Riverpod问题的颤动区域?

huwehgph  于 2022-09-27  发布在  Hive
关注(0)|答案(1)|浏览(113)

我正在使用配置单元和app_profile数据模型将应用程序设置存储在本地数据库中,并使用riverpod调用HivedataStore(depencdcy注入)。问题是,当我更新本地类型的配置单元框时,需要重新启动应用程序才能生效,但如果我将Theme更新为Dark,它就会正常工作。我的代码如下:
主零件

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // await AppAssets.preloadSVGs();
  final dataStore = HiveDataStore();
  await dataStore.init();
  await dataStore.createDefaultProfile(
      appProfile: AppProfile(
    onBoardingCompleted: false,
    locale: 'en',
    themeMode: ThemeModeCustomized.light,
  ));

  runApp(ProviderScope(overrides: [
    hiveDataStoreProvider.overrideWithValue(dataStore),
  ], child: const MyApp()));
}

hive_data_store.dart文件

class HiveDataStore {
  static const profileBoxName = 'appProfile';
  static const themeColor = 'themeColor';

  Future<void> init() async {
    await Hive.initFlutter();

    Hive.registerAdapter<AppProfile>(AppProfileAdapter());
    Hive.registerAdapter(ThemeModeCustomizedAdapter());

    await Hive.openBox<AppProfile>(profileBoxName);
  }

  Future<void> createDefaultProfile({
    required AppProfile appProfile,
  }) async {
    final box = Hive.box<AppProfile>(profileBoxName);
    if (box.isEmpty) {
      await box.put('0', appProfile);
    } else {
      print('box already have these Values : ${box.get(0)?.locale}');

    }
  }

  Future<void> updateBox({
    bool? onBoardingCompleted,
   String? locale,
    ThemeModeCustomized? themeMode,
  }) async {
    final box = Hive.box<AppProfile>(profileBoxName);
    final userProfile = box.get('0');
    final newProfile = userProfile!.copyWith(
        onBoardingCompleted: onBoardingCompleted,
        locale: locale,
        themeMode: themeMode);
    await box.put('0', newProfile);
  }

  AppProfile? appProfile() {
    final box = Hive.box<AppProfile>(profileBoxName);
    return box.get(0);
  }

  ValueListenable<Box<AppProfile>> appProfileListenable() {
    return Hive.box<AppProfile>(profileBoxName).listenable();
  }
}

final hiveDataStoreProvider = Provider<HiveDataStore>((ref) {
  throw UnimplementedError();
});

我的应用程序.dart

class MyApp extends ConsumerWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {

    final provider = ref.watch(hiveDataStoreProvider);
    return ValueListenableBuilder(
        valueListenable: provider.appProfileListenable(),
        builder: (context, Box<AppProfile> box, __) {
          print('myapp rebuilds listenablebuilder');
          final appProfile =  box.get('0');
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            localizationsDelegates: AppLocalizations.localizationsDelegates,
            supportedLocales: AppAssets.getLocals(appProfile!),
            onGenerateTitle: (context) {
              var t = AppLocalizations.of(context);
              return t!.appTitle;
            },
            themeMode: AppAssets.themeModeGeter(appProfile),
            theme: ThemeData.light(),
            darkTheme: ThemeData.dark(),
            initialRoute: '/',
            routes: {
              '/': (context) {
                return  const HomePage();
              }
            },
          );
        });
  }
}

主页.dart

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    print('homepage rebuils');
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context)!.appTitle),
      ),
      body: Center(
        child: Consumer(builder: (context, WidgetRef ref, __) {
          return Column(
            children: [
              TextButton(
                  onPressed: () {
                    ref.read(hiveDataStoreProvider).updateBox(
                          locale: 'ar', themeMode: ThemeModeCustomized.dark
                        );
                  },
                  child: const Text('العربية')),
              TextButton(
                  onPressed: () {
                    ref.read(hiveDataStoreProvider).updateBox(
                          locale: 'en', themeMode: ThemeModeCustomized.light
                        );
                  },
                  child: const Text('English')),
            ],
          );
        }),
      ),
    );
  }
}

我认为MyApp类中需要更改一些内容,我使用ValueListenableBuilder,因为我在Hive官方软件包页面中看到了它。为什么需要重新启动应用程序才能对区域设置生效?与完美工作的应用程序主题不同。
这是我的申请资产。省道代码(只是额外信息):

class AppAssets {

  static List<Locale> getLocals(AppProfile appProfile) {
    switch (appProfile.locale) {
      case 'ar':
        return [const Locale('ar', '')];

      case 'en':
        return [const Locale('en', '')];
      case '':
        return AppLocalizations.supportedLocales;
      default:
        return AppLocalizations.supportedLocales;
    }
  }

  static ThemeMode themeModeGeter(AppProfile? appProfile) {
    switch (appProfile?.themeMode.name) {
      case 'dark':
        {
          return ThemeMode.dark;
        }

      case 'light':
        {
          return ThemeMode.light;
        }

      case 'system':
        {
          return ThemeMode.system;
        }
      default:
        ThemeMode.system;
    }
    return ThemeMode.system;
  }

}
qoefvg9y

qoefvg9y1#

我的错误是,我在更新supportedLocales时没有在MaterialApp小部件中更新e1c1d1e,我将保留这个问题,尽管它可能会给其他人一些提示。。

supportedLocales: AppAssets.getLocals(appProfile),
 locale: Locale('$appProfile.locale',''),

相关问题