この例を確認してください。共有設定値を保存してから撤回する方法を説明する例を作成しました
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'),
],
),
),
);
}
}
それが機能するかどうか教えてください。