【发布时间】: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