关闭时保存页面状态

Save state of the page when closed

我有三页。第三页获取文本输入并将其传递给第二页的文本小部件。当第二页关闭并再次打开时,以前的数据丢失了。我想在页面关闭时保存数据。

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You are welcome',style: (TextStyle(fontWeight: FontWeight.bold, fontSize: 15,color: Colors.black)),
            ),
            RaisedButton.icon(
              label: Text("Go to second page",style: (TextStyle(fontWeight: FontWeight.bold, fontSize: 18,color: Colors.white)),),
              icon: Icon(Icons.pages),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => SecondPage()),
                );
              },
              color: Colors.red,

            ),
          ],
        ),
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  @override
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
  String _information = 'No Information Yet';

  void updateInformation(String information) {
    setState(() => _information = information);
  }

  void moveToSecondPage() async {
    final information = await Navigator.push(
      context,
      CupertinoPageRoute(
          fullscreenDialog: true, builder: (context) => ThirdPage()),
    );
    updateInformation(information);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Page"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
                _information,style: (TextStyle(fontWeight: FontWeight.bold, fontSize: 15,color: Colors.black))
            ),
            SizedBox(
              height: 8.0,
            ),
            RaisedButton(
              color: Colors.purple,
              child: Text(
                'Get Information',
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                moveToSecondPage();
              },
            )
          ],
        ),
      ),
    );
  }
}


class ThirdPage extends StatelessWidget {
  final TextEditingController textController = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextField(
                  autofocus: true,
                  style: TextStyle(fontSize: 20.0),
                  controller: textController,
                ),
              ),
              SizedBox(
                height: 8.0,
              ),
              RaisedButton(
                child: Text(
                  'Submit',
                  style: TextStyle(color: Colors.white),
                ),
                color: Colors.blue,
                onPressed: () {
                  Navigator.pop(context, textController.text);
                },
              )
            ],
          )),
    );
  }
}

在多次调用小部件之间保持变量值

创建模型

在这种情况下,您可以创建一个不同的 class(模型) 有(静态)信息字符串,然后在第二页导入它。 这样整个项目就只有一个实例了。

通过将字符串设为静态,您无需创建实例对象即可访问它。

class Information extends ChangeNotifier {

    static String _information = 'Default Value';

    get information {
        // Any aditional functionality
        return _information;
    }

    set setInformation (String value) {
        // Any additional functinality
        _information = value;
        notifyListeners();
    }

}

使用模型

您必须使用更改通知程序提供程序来提供此信息。

您必须将要在其中使用信息的小部件包装起来 消费者小部件。点击她了解更多信息 click here to learn more about statemanagement

您可以使用 getter 和 setter,就好像它们只是 class

的成员一样

您可以通过写作

获取信息

Information.information;

并通过写入设置信息

Information.setInfromation = 'new Information';

希望对您有所帮助。

你的问题已经 several times already. The answer is up to you. This is a state management 了。这是一个非常大的领域,您需要了解并选择一种状态管理解决方案,然后将其应用到您的应用中。

但是,您可以使用包装器 类、映射、全局变量在页面之间传递状态。不建议这样做,并且会随着您的应用程序的增长而导致问题。这是一个使用 wrapper class 在页面之间传递字符串值的解决方案。

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class InformationWrapper {
  String data = 'No Information Yet';
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  InformationWrapper _information = InformationWrapper();
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You are welcome',
              style: (TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 15,
                  color: Colors.black)),
            ),
            RaisedButton.icon(
              label: Text(
                "Go to second page",
                style: (TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 18,
                    color: Colors.white)),
              ),
              icon: Icon(Icons.pages),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => SecondPage(
                            information: widget._information,
                          )),
                );
              },
              color: Colors.red,
            ),
          ],
        ),
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  final InformationWrapper information;

  const SecondPage({Key key, this.information}) : super(key: key);
  @override
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
  void updateInformation(String information) {
    setState(() => widget.information.data = information);
  }

  void moveToSecondPage() async {
    final information = await Navigator.push(
      context,
      CupertinoPageRoute(
          fullscreenDialog: true, builder: (context) => ThirdPage()),
    );
    updateInformation(information);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Page"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(widget.information.data,
                style: (TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 15,
                    color: Colors.black))),
            SizedBox(
              height: 8.0,
            ),
            RaisedButton(
              color: Colors.purple,
              child: Text(
                'Get Information',
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                moveToSecondPage();
              },
            )
          ],
        ),
      ),
    );
  }
}

class ThirdPage extends StatelessWidget {
  final TextEditingController textController = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              autofocus: true,
              style: TextStyle(fontSize: 20.0),
              controller: textController,
            ),
          ),
          SizedBox(
            height: 8.0,
          ),
          RaisedButton(
            child: Text(
              'Submit',
              style: TextStyle(color: Colors.white),
            ),
            color: Colors.blue,
            onPressed: () {
              Navigator.pop(context, textController.text);
            },
          )
        ],
      )),
    );
  }
}