【问题标题】:Storing List Variable on change在更改时存储列表变量
【发布时间】:2020-09-16 14:49:12
【问题描述】:

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

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

ma​​in.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,但它似乎有点矫枉过正,所以我不确定我的其他选择。任何帮助将不胜感激!

【问题讨论】:

标签: flutter dart data-persistence


【解决方案1】:

您可以使用SharedPreferences 包或任何其他能够在应用启动之间保留数据的方法。有关持久化数据的选项,请参阅 this

选项:

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

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

附带说明,bookmarked = bookmarked; 行没有用。

【讨论】:

  • 谢谢!我将尝试 SharedPreferences 部分。虽然,我怎么能读/写列表到文件?我知道在 Java 中,您可以将列表序列化为对象以将其保存到文件中。可以对 Dart 中的列表执行类似的操作吗?虽然我喜欢 SharedPreferences,但我想存储的不仅仅是字符串。
  • @Shiv 你可以做同样的事情并在 dart 中序列化数据。这不是必需的,因为您可以将数据写入文件,它不必是字符串。您还可以将其他常见数据类型存储在 Shared Preferences 中,但您也可以将任何数据序列化并将其作为字符串存储在 Shared Preferences 中。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 2021-06-09
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多