sharedpreferences - 如何在 flutter 中保存和加载对其他页面的共享偏好

标签 sharedpreferences flutter

我试图从标签栏页面保存并共享一个可变的电话号码字符串到主页。目前我的变量仅在重新加载后显示。我试图在保存后立即显示变量。

我的代码:

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);
              }
             }
            );
          }
        )
       ],
     ),
   );
  }
}

最佳答案

为了达到你想要的效果,你需要从PhonePage类中调用MyHomePage类的_loadvariable()函数。为此:

重构并从 _loadvariable()_MyHomePageState 中删除 _,这样它就不再是私有(private)的。 将 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();
}

关于sharedpreferences - 如何在 flutter 中保存和加载对其他页面的共享偏好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50426229/

相关文章:

android - 尝试写入文件: "OS Error: Operation not permitted, errno = 1"?时如何解决Flutter错误

android - 空格时Flutter String.contains(substring)失败

arrays - 错误:未为类 'datauser'定义 setter/getter '_MyHomePageState'

java - 某些设备上的 getSharedPreferences 空指针异常

java - Android,适配器中的共享首选项

android - 使用 SharedPreferences 保存用户数据

android - 如何显示以前的 EditText 用户输入以及最近的 EditText 用户输入?

java - 想了解共享偏好限制

Flutter 列滚动变得非常滞后,行数更高

flutter - 像 iOS 一样的音量小部件 - Flutter