sharedpreferences - 如何在颤动中保存和加载共享偏好到另一个页面
问题描述
我试图将一个可变的电话号码字符串从标签栏页面保存并共享到主页。目前我的变量仅在重新加载后显示。我试图在保存后显示变量。
我的代码:
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,
),
);
}
}
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> {
String _variable;
@override
void initState() {
super.initState();
_loadvariable();
}
_loadvariable() async { // load variable
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_variable = (prefs.getString('variable'));
}
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
bottomNavigationBar: BottomAppBar(
color: Colors.blue,
elevation: 20.0,
child: ButtonBar(
alignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(Icons.phone),
color: Colors.white,
onPressed: () {
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new Phone_Page()),
);
},
),
],
),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'$_variable',
style: Theme.of(context).textTheme.display1,
),
],
),
),
);
}
}
这是我的第二页类,我可以点击电话图标显示一个对话框,我可以在文本字段上书写。单击保存按钮后,我的文本字段被保存,对话框关闭,我的变量显示在卡上。但是在主页返回后,我的变量没有显示。我需要重新加载应用程序才能显示它:(
class Phone_Page extends StatefulWidget {
@override
Phone_PageState createState() => Phone_PageState();
}
class Phone_PageState extends State<Phone_Page> {
final TextEditingController controller = new TextEditingController();
String _variable;
_loadvariable() async { // load variable
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_variable = (prefs.getString('variable'))?? "";
});
}
_savevariable() async { // save variable
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
prefs.setString('variable', controller.text);
});
}
_deletevariable() async { //delete variable
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
prefs.remove('variable');
});
}
@override
void initState() {
super.initState();
_loadvariable()?? "";
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Phone"),
),
body: new Center(
child: new ListView(
children: <Widget>[
new Card(
child: new Container(
padding: const EdgeInsets.all(20.0),
child: new Row(
children: [
new Expanded(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
new Text(
'$_variable',
style: new TextStyle(
color: Colors.grey[500],
),
),
],
),
),
new IconButton(
icon: new Icon(Icons.add_call),
onPressed: ()
{
_showDialog();
}
),
new IconButton(
icon: new Icon(Icons.delete),
onPressed: () { setState(() {
_deletevariable();
_savevariable();
_loadvariable();
}
);
},
),
],
),
),
),
]
)
)
);
}
_showDialog() async {
await showDialog<String>(
context: context,
child: new AlertDialog(
// contentPadding: const EdgeInsets.all(16.0),
content: new Row(
children: <Widget>[
new Expanded(
child: new TextField(
controller: controller,
autofocus: true,
decoration: new InputDecoration(
labelText: 'number', hintText: '06 - - - - - - - -'),
// keyboardType: TextInputType.number,
),
)
],
),
actions: <Widget>[
new FlatButton(
child: const Text('save'),
onPressed: (){
setState(() { {
_savevariable();
Navigator.pop(context);
}
}
);
}
)
],
),
);
}
}
解决方案
要实现你想要的,你需要从类中调用_loadvariable()
类的函数。要做到这一点:MyHomePage
PhonePage
_
重构并从中删除_loadvariable()
,_MyHomePageState
使其不再是私有的。MyHomePageState
将类实例传递给PhonePage
如下:
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new PhonePage(
myHomePageState: this,
)),
);
在 _savevariable() 中调用 loadvariable() 就像
_savevariable() async {
// save variable
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
prefs.setString('variable', controller.text);
});
widget.myHomePageState.loadvariable();
}
确保 myHomePageState 类型为 var,这样您就不会收到类型错误:
class PhonePage extends StatefulWidget {
var myHomePageState;
PhonePage({this.myHomePageState});
@override
PhonPageState createState() => PhonPageState();
}
推荐阅读
- html - 我们可以在不使用类和 ID 的情况下使用 div 标签设置字体系列、字体大小吗?它被认为是好还是坏的做法?
- python - Python Scrapy Pipeline 编辑最后一项?
- vim - 为不起作用的 vim 功能添加了新脚本
- python - Pandas:将数据解析成列
- postgresql - 如何设置 RabbitMQ 以跨消费者处理同一资源上的异步任务,例如数据库更新?
- postgresql - TypeORM PostgreSQL 选择 JSON 字段等于某个值的位置
- python - 在另一个函数中使用一个函数并且很难使用循环/参数
- python - 我可以将nosetests 命令行选项放在配置文件中吗?
- kubernetes - 无法将工作节点加入k8中的主节点
- json - Flutter:FutureBuilder 类型“FormatException”不是“Widget”类型的子类型