首页 > 解决方案 > 如何在颤动中保存和加载共享偏好到另一个页面

问题描述

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

我的代码:

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

标签: sharedpreferencesflutter

解决方案


要实现你想要的,你需要从类中调用_loadvariable()类的函数。要做到这一点:MyHomePagePhonePage

_重构并从中删除_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();
}

推荐阅读