Flutter get_storage未保存数据

pod7payv  于 2023-04-22  发布在  Flutter
关注(0)|答案(1)|浏览(168)

我试图保存我的应用程序的主题使用bool变量在获取存储。但每当我重新启动或关闭应用程序后打开应用程序,变量得到空。

void changeTheme() {
    final box = GetStorage();
    box.writeIfNull('isDark', false);
    bool isDark = box.read('isDark');
    isDark
        ? Get.changeTheme(QRCodeTheme.lightThemeData)
        : Get.changeTheme(QRCodeTheme.darkThemeData);
    box.write('isDark', !isDark);
  }
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  Prefs.init();
  runApp(QRCodeScannerApp());
}

class QRCodeScannerApp extends StatefulWidget {
  QRCodeScannerApp({Key? key}) : super(key: key);

  @override
  State<QRCodeScannerApp> createState() => _QRCodeScannerAppState();
}

class _QRCodeScannerAppState extends State<QRCodeScannerApp> {
  bool darkMode = false;
  @override
  void initState() {
    final box = GetStorage();
    box.writeIfNull('isDark', false);
    darkMode = box.read('isDark');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      theme:
          darkMode ? QRCodeTheme.darkThemeData : QRCodeTheme.lightThemeData,
      initialRoute: AppRoutes.home,
      getPages: [
        GetPage(
          name: AppRoutes.home,
          page: () => HomePage(),
        ),
      ],
    );
  }
}

我错过了什么?提前感谢!

cygmwpex

cygmwpex1#

在您的void main中,请输入以下代码

await GetStorage.init();

您应该添加await关键字
P.S:-在你的情况下,你用写await Prefs.init()

相关问题