在更改时存储列表变量

Storing List Variable on change

我目前正在学习 Flutter 并正在制作一个个人理财应用程序。我可以选择为我的指南添加书签,然后在书签选项卡上查看它们。现在,我正在使用一个列表来简单地存储指南的名称并将它们显示为列表图块。

我遇到的问题是,每当应用程序 运行 更新书签列表时,书签页面都会加载正确的信息,但是当我关闭并重新启动应用程序时,它又回到原来的状态初始状态为空。我该如何修复它以便应用程序保存已添加书签的标签页?

main.dart

List<String> bookmarked = [];

String introInfo = """ <h1>Introduction!</h1>
<p><strong><em>NOTE: The guides are U.S. specific but most information can be applied in most countries outside the U.S.</em></strong></p>
<p>The guides in this app will teach you the basics of personal finance.</p>
<p>Financial knowledge is something that is invaluable but the U.S. education system does not put much emphasis on it. If you are looking to get into personal finance, you're at the right place.</p>""";

void main() {
  runApp(MaterialApp(
    initialRoute: '/',
    routes: {
      '/': (context) => MyApp(),
      '/finTable': (context) => FinNav(),
      '/disclaimer': (context) => Disclaimer(),
      '/intro': (context) => GuideStyle(guideName: 'introduction',guideInfo: introInfo, isFav: bookmarked.contains('introduction'),),
      '/budget': (context) => GuideStyle(guideName: 'budget',guideInfo: introInfo, isFav: bookmarked.contains('budget'),),
      '/bookmark': (context) => Bookmarks(),
    },
    theme: ThemeData(fontFamily: 'Raleway'),
  ));
}

/* I have a stateless widget that shows all pages and navigates to one the user selects */

guidestyle.dart

class GuideStyle extends StatelessWidget {
  String guideName;
  String guideInfo; 
  Widget previous;
  Widget next;
  bool isFav;
  GuideStyle({this.guideName,this.guideInfo, this.isFav });//this.next, this.previous});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color.fromRGBO(220, 20, 60, 1.0),
          title: Text('Introduction'),
          centerTitle: true,
          elevation: 10.0,
          actions: <Widget>[
            Padding(
              padding: const EdgeInsets.fromLTRB(0.0,2.0,50.0,0.0),
              child: MyStatefulWidget(isFav: isFav,name: guideName,),
            ),
          ],
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: RaisedButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text('Back'),
                textColor: Colors.white,
                color: Color.fromRGBO(220, 20, 60, 0.8),
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: HtmlWidget(
                    guideInfo,
                  )
                ),
              ),
            ),
          ],
        ));
  }
}


class MyStatefulWidget extends StatefulWidget {
  bool isFav;
  String name;
  MyStatefulWidget({Key key, this.isFav, this.name}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        IconButton(
          icon: widget.isFav ? Icon(Icons.bookmark, color: Colors.black) : Icon(Icons.bookmark_border),
          onPressed: () {
            setState(() {
              widget.isFav = !widget.isFav;
              if(widget.isFav){
                bookmarked.add(widget.name);
                bookmarked = bookmarked;
              }else{
                bookmarked.remove(widget.name);
                bookmarked = bookmarked;
              }
            });
          },
        ),
      ],
    );
  }
}

如前所述,guidestyle.dart 会在应用处于 运行 时更新列表,但当应用重新启动时会重置列表。

我正在考虑使用 sqflite,但它似乎有点过分,所以我不确定我的其他选择。如有任何帮助,我们将不胜感激!

您可以使用 SharedPreferences package or any other method that is able to persist data between app launches. See this 选项来保存数据。

选项:

  • 使用 SQLite 持久化数据(虽然你不想使用它,但它仍然是一个选项)
  • 读写文件
  • 在磁盘上存储键值数据(SharedPreferences) - 这是最简单的,可能会很好地满足您的需要

如果您使用 SharedPreferences,setStringList 方法将完全满足您的需求。

作为旁注,bookmarked = bookmarked; 行没有用。

List<String> bookmarked = []; 这总是初始化你的数据为空
首先,您需要存储包 shared_preferences 或 sqflite 等..
您可以在这里找到 => https://pub.dev/
然后检查数据是否存在。
之后,if(hasData) bookmarked = "loaded data" else bookmarked = [];