Flutter:使用共享首选项打开/关闭Flutter本地通知时,保存图标状态



我正在使用以下代码来打开/关闭flutter本地通知。此代码运行良好,但当应用程序关闭并重新打开时,图标状态不会被保存。

我需要使用共享偏好插件保存当前选择的图标,但我无法做到这一点。

有人能帮我把共享偏好添加到这个代码中吗。

这个变量:

var _icon2 = Icons.notifications_off;

这是在开/关之间运行功能的图标代码:

IconButton(
icon: Icon(
_icon2,
color: Colors.blue,
size: 30,
),
onPressed: () {
setState(() {
if (_icon2 == Icons.notifications_off) {
_icon2 = Icons.notifications_active;
_repeatNotification2();
} else {
_icon2 = Icons.notifications_off;
_cancelNotification2();
}
});
},
),

我设法将共享首选项添加到代码中。


import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
class SimpleBooleanScreen extends StatefulWidget {
@override
SimpleBooleanScreenState createState() => SimpleBooleanScreenState();
}
class SimpleBooleanScreenState extends State<SimpleBooleanScreen> {
IconData _FirstIcon = Icons.notifications_active;
bool isIconOneActive = true;
String keyNameOne = "_updateScreenOneState";
Future<bool> loadDataOne() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
return preferences.getBool(keyNameOne) ?? true;
}
Future<bool> saveDataOne() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
return preferences.setBool(keyNameOne, isIconOneActive);
}
setData() async {
loadDataOne().then((value) {
setState(() {
isIconOneActive = value;
setIcon();
});
});
}
setIcon() async {
if (isIconOneActive) {
_FirstIcon = Icons.notifications_active;
} else {
_FirstIcon = Icons.notifications_off;
}
}
@override
void initState() {
setData();
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(''),
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Center(
child: Column(
children: <Widget>[
ListTile(
title: Text('Notificaation 1',
style: TextStyle(fontSize: 26.0)),
trailing: IconButton(
icon: Icon(
_FirstIcon,
size: 40.0,
color: Colors.blue,
),
onPressed: () {
setState(() {
if (isIconOneActive) {
isIconOneActive = false;
setIcon();
saveDataOne();
_cancelNotification1();
} else {
isIconOneActive = true;
setIcon();
saveDataOne();
_repeatNotification1();
}
});
},
),
),
],
),
),
),
),
),
);
}

相关内容

  • 没有找到相关文章

最新更新