我正在尝试从更改通知程序中了解共享首选项包。这是我的代码:
Future<void> main() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => GlobalSettings1(prefs: prefs)),
],
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
'/': (context) => Page01(),
});
}
}
class Page01 extends StatefulWidget {
const Page01({Key? key}) : super(key: key);
@override
State<Page01> createState() => _Page01State();
}
class _Page01State extends State<Page01> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(height: 30,),
InkWell(
onTap: () {
context.read<GlobalSettings1>().ToggleSwitch();
},
child: Container(
height: 30,
width: 80,
color: context.watch<GlobalSettings1>().toggleSwitch01
? Colors.green
: Colors.red,
),
),
],
),
);
}
}
这是我的更改通知程序:
class GlobalSettings1 with ChangeNotifier {
bool _toggleSwitch01 = true;
final SharedPreferences prefs;
GlobalSettings1({required this.prefs});
bool get toggleSwitch01 => _toggleSwitch01;
void ToggleSwitch() {
_toggleSwitch01 = !_toggleSwitch01;
_setPrefItems();
notifyListeners();
}
void _setPrefItems() {
prefs.setBool('toggleSwitch01', _toggleSwitch01);
notifyListeners();
}
void _getPrefItems() {
_toggleSwitch01 = prefs.getBool('toggleSwitch01') ?? true;
notifyListeners();
}
bool getToggleSwitch01() {
_getPrefItems();
return _toggleSwitch01;
}
}
我如何在我的代码中使用 setprefitems 和 getprefitems 来制作它以便在应用程序关闭然后再次启动时保存 toggleswitch01 bools 状态?
非常感谢