【发布时间】:2019-06-16 15:50:35
【问题描述】:
如何读取 sharedPreference 并使用结果设置开关?
我正在尝试开发一个可以检查的项目列表,并使用 sharedPreferences 保存每个开关的状态。
我想我正在存储这些值,但我无法获取代码来读取 sharedPreference 文件并设置开关
我已经搜索过,但我的问题非常独特,我找不到解决方案。
class CheckList extends StatefulWidget {
@override
_CheckListState createState() => _CheckListState();
}
bool isSwitched = false;
class _CheckListState extends State<CheckList> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Card(
margin: EdgeInsets.symmetric(vertical: 15.0, horizontal: 35.0),
child: ListView(
children: <Widget>[
SizedBox(height: 20,),
Text('Check List', style: TextStyle(fontSize: 25, color: Colors.green), textAlign: TextAlign.center,),
SizedBox(height: 10),
CheckItem('Deposit Paid', 'Deposit'),
SizedBox(height: 10),
CheckItem('Balance Paid', 'Balance'),
SizedBox(height: 10),
CheckItem('Uploaded Team Name','Team'),
SizedBox(height: 10),
CheckItem('Uploaded Charity','Charity'),
SizedBox(height: 10),
CheckItem('Sent Copy of Leader Passport','Passport'),
SizedBox(height: 10),
CheckItem('Log book in Team Members name','LogBook'),
SizedBox(height: 10),
CheckItem('Rally Insurance Printed out','Insurance'),
SizedBox(height: 10),
CheckItem('MOT printed out', 'Mot'),
SizedBox(height: 10),
CheckItem('Fueled up and Ready to go', 'Ready'),
SizedBox(height: 10),
],
)
),
);
}
}
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class CheckItem extends StatefulWidget {
CheckItem(this.txt, this.checkKey);
final String txt;
final String checkKey;
@override
_CheckItemState createState() => _CheckItemState();
}
bool isSwitched = false;
class _CheckItemState extends State<CheckItem> {
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Text(
widget.txt,
style: TextStyle(
fontFamily: 'sans pro',
color: Colors.white,
letterSpacing: 2.0,
fontWeight: FontWeight.bold,
fontSize: 15.0,
),
)),
SizedBox(
width: 20.0,
),
Switch(
value: isSwitched,
onChanged: (value) {
setState(() {
isSwitched = value;
putShared(widget.checkKey, value);
});
},
activeTrackColor: Colors.lightGreenAccent,
activeColor: Colors.green,
),
],
),
);
}
}
void putShared(String key, bool val) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool(key, val);
}
Future getShared(String key) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool val = prefs.getBool(key);
return val;
}
代码似乎有效,但我无法确定,因为我无法读取共享首选项并设置开关。
【问题讨论】:
-
这是太多无关的代码,而且问题本身相当广泛。您已经有
getShared和putShared方法可以使用SharedPreferences。究竟是什么问题?