【问题标题】:i gad an error in my simple app says Unhandled Exception: Null check operator used on a null value我在我的简单应用程序中出现错误说未处理的异常:空值检查运算符用于空值
【发布时间】:2022-07-26 00:30:17
【问题描述】:

当我尝试使用共享首选项在暗模式和亮模式之间切换时出现错误我需要插入一个类似 false 的布尔值作为示例,并且我需要在重新启动应用程序时布尔值保持不变

这是我需要更改主题模式的页面

这是我在里面做bool的文件

void main() async {
  // since the main is async and await you have to put this method to make sure that the await methods is done and then eunning the app
  WidgetsFlutterBinding.ensureInitialized();

  DioHelper.init(); // this one here is to create the dio object
  await CacheHelper.init(); // this one here is to create the SP object
  bool? isDark = CacheHelper.getBoolian(key: 'isDark');
  runApp(MyApp(isDark!));
}

class MyApp extends StatelessWidget {
  final bool isDark;

  const MyApp(this.isDark, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) => AppCubit()
        ..changeAppMode(
          fromShared: isDark,
        ),
      child: BlocConsumer<AppCubit, AppStates>(
        listener: (context, state) {},
        builder: (context, state)

我用的是cubit所以这是我改变模式的方法

bool isaDarkMode = true;

  void changeAppMode({bool? fromShared}) {
    if (fromShared != null) {
      isaDarkMode = fromShared;
      emit(AppChangeMoadeState());
    } else {
      isaDarkMode = !isaDarkMode;
    }
    // here iam inserting a data into the SP method to save it there
    CacheHelper.putBoolian(key: ' isaDarMode', value: isaDarkMode)
        .then((value) {
      emit(AppChangeMoadeState());
      print('Emit and INSERTING done successfully');
    });
  }
}

这是共享偏好方法

import 'package:shared_preferences/shared_preferences.dart';

// here Iam creating the method of Shared Prefrences
class CacheHelper {
  static SharedPreferences? sharedPreferences;

  //This method is to define the shared prefrence
  static init() async {
    sharedPreferences = await SharedPreferences.getInstance();
  }

  // this one is for insert a data into the SP(SharedPrefrences)
  static Future<bool> putBoolian({
    required String key,
    required bool value,
  }) async {
    return await sharedPreferences!.setBool(key, value);
  }

  // this one is for get a data into the SP
  static bool? getBoolian({
    required String key,
  }) {
    return sharedPreferences!.getBool(key);
  }
}

【问题讨论】:

  • isDark != isaDarMode

标签: flutter dart sharedpreferences cubit


【解决方案1】:

用默认值试试

bool? isDark = CacheHelper.getBoolian(key: 'isDark');
runApp(MyApp(isDark??false));

【讨论】:

    猜你喜欢
    • 2021-08-19
    • 1970-01-01
    • 2021-07-22
    • 2021-11-21
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多