Reputation: 169
I am using the following code to switch flutter local notifications on/off. This code works fine, but the icon state does not get saved when the app is closed and reopen.
I need to get this current selected icon saved using shared preferences plugin, but I could not manage to do that.
Can someone help me to add shared preferences to this code.
This the variable:
var _icon2 = Icons.notifications_off;
This is the code of the icons which run the functions between on/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();
}
});
},
),
Upvotes: 0
Views: 499
Reputation: 169
I managed to add shared preferences to the code.
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();
}
});
},
),
),
],
),
),
),
),
),
);
}
Upvotes: 1