Reputation: 61
So I created a categories section in my app where you can select multiple categories by clicking on the container. The container you select changes colour. What I want to do is save the choices selected using shared preferences and display it again whenever user wants to see his selected categories.
return GestureDetector(
onTap: () {
setState(() {
if (isSelected == false) {
isSelected = !isSelected;
color = widget.color;
print('Coming here');
} else {
isSelected = false;
color = Colors.white;
}
prefs.setBool(_key, isSelected);
});
},
child: AnimatedContainer(
padding: EdgeInsets.all(widget.padding),
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
),
duration: Duration(milliseconds: 500),
child: Container(
child: Text(
widget.labelText,
style: TextStyle(
color: kLightBlue,
fontFamily: 'clanproBold',
fontSize: SizeConfig.blockSizeHorizontal * 3),
),
),
),
);
This is the code to create multiple containers. How can I save the options?
Upvotes: 4
Views: 10111
Reputation: 3767
Just check this example I have created an example that will tell you how to save the shared preferences value and then retrieve it
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Users'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool isSelected = false;
String stringValue = "No value";
@override
void initState() {
super.initState();
getAllSavedData();
// You can use the initState where you can get all the saved categories and the assign it based on it.
}
getAllSavedData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool value = prefs.getBool("youKey");
// For first time you get null data so no value
// is assigned so it will not assign anything
if (value != null) stringValue = value.toString();
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
GestureDetector(
onTap: () async {
if (isSelected == false) {
isSelected = !isSelected;
//color = Colors.pink;
print('Coming here');
} else {
isSelected = false;
// color = Colors.white;
}
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("youKey", isSelected);
// This is where you save the data and then when the user second time opens he will get the stoared data
setState(() {});
},
child: AnimatedContainer(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
duration: Duration(milliseconds: 500),
child: Container(
child: Text(
'S',
style: TextStyle(
color: Colors.blue,
fontFamily: 'clanproBold',
fontSize: 20),
),
),
),
),
// This is when you open the screen for second time you get the value as true
Text('This is the value you saved $stringValue'),
],
),
),
);
}
}
Let me know if it works.
Upvotes: 1
Reputation: 632
First of all, you have to add the dependency of shared preferences
at your pubspec.yaml
file as follows:
dependencies:
flutter:
sdk: flutter
shared_preferences: "<newest version>"
After that you have to import to your class the package:
import 'package:shared_preferences/shared_preferences.dart';
Then at the state, you want to save the options add the following code:
_saveOptions() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool('option', true);
}
You can read the data you saved at SharedPreferences using the following code:
SharedPreferences prefs = await SharedPreferences.getInstance();
bool boolValue = prefs.getBool('option');
Important: You can only save int, String, double or bool variables using SharedPreferences.
So if you want to save the options the user gives, you can use only the types above. You can make it work by passing the values of the options as String or int to SharedPrefrences and convert them back again.
Example:
Color color = new Color(0x#BD452C);
int colorValue = color.value;
String colorString = color.toString();
Color newColor = new Color(colorValue);
Upvotes: 5