【问题标题】:How do I save data after closing the Flutter app?关闭 Flutter 应用后如何保存数据?
【发布时间】:2020-06-29 15:59:35
【问题描述】:

我尝试创建一个应用程序,您可以在其中简单地添加一个新的 TODO。我的问题是,在添加了一个新的 TODO 之后,然后关闭我的应用程序,我的 TODO-List 是空的。在应用程序中保存数据的最佳方式是什么?有什么简单的解决方案吗?

【问题讨论】:

    标签: flutter dart state-management


    【解决方案1】:

    只需查看我创建的这个示例待办事项列表代码。

    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({Key key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: Container(
              child: TODOApp(),
            ),
          ),
        );
      }
    }
    
    class TODOApp extends StatefulWidget {
      TODOApp({Key key}) : super(key: key);
    
      @override
      _TODOAppState createState() => _TODOAppState();
    }
    
    class _TODOAppState extends State<TODOApp> {
      TextEditingController _todoController = TextEditingController();
      List<String> todoList = List();
      bool _isLoading = false;
    
      _saveList(list) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
    
        prefs.setStringList("key", list);
    
        return true;
      }
    
      _getSavedList() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        if (prefs.getStringList("key") != null)
          todoList = prefs.getStringList("key");
        setState(() {});
      }
    
      @override
      void initState() {
       
        super.initState();
        setState(() {
          _isLoading = true;
        });
        _getSavedList();
    
        setState(() {
          _isLoading = false;
        });
      }
    
      Future<bool> _onWillPop() async {
        return (await showDialog(
              context: context,
              builder: (context) => new AlertDialog(
                title: new Text('Are you sure?'),
                content: new Text('Do you want to exit an App'),
                actions: <Widget>[
                  new FlatButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: new Text('No'),
                  ),
                  new FlatButton(
                    onPressed: () {
                      _saveList(todoList);
                      Navigator.of(context).pop(true);
                    },
                    child: new Text('Yes'),
                  ),
                ],
              ),
            )) ??
            false;
      }
    
      @override
      Widget build(BuildContext context) {
        return WillPopScope(
          onWillPop: _onWillPop,
          child: SafeArea(
            child: _isLoading
                ? Center(
                    child: CircularProgressIndicator(),
                  )
                : Container(
                    child: Column(
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: TextField(
                            decoration: InputDecoration(
                              hintText: 'Add Items',
                            ),
                            controller: _todoController,
                            onSubmitted: (text) {
                              // do what you want with the text
                              todoList.add(_todoController.text);
                              _todoController.clear();
                              setState(() {});
                            },
                          ),
                        ),
                        todoList == null
                            ? Container(
                                child: Center(
                                  child: Text('Please Add the items'),
                                ),
                              )
                            : ListView.builder(
                                shrinkWrap: true,
                                itemCount: todoList.length,
                                itemBuilder: (BuildContext context, int index) {
                                  return Card(
                                    child: Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Text(todoList[index]),
                                    ),
                                  );
                                },
                              ),
                      ],
                    ),
                  ),
          ),
        );
      }
    }
    
    

    如果它有效,请告诉我

    【讨论】:

    • 您好,感谢您的回答。我已经尝试过了,它工作正常。 Bur没有其他解决方案如何在没有共享偏好的情况下做到这一点?
    • 共享偏好基本上是针对轻量级的东西,如果你在更大的平台上使用本地数据库是首选。
    • 你知道如何保存 List> 吗?只能使用 prefs.setStringList() 保存 StringList
    • 这可能是不可能的,我没有检查,但目前正忙于工作,很快就会让你知道。
    • 在此之前您可以查看此链接:stackoverflow.com/questions/62657223/…
    【解决方案2】:

    作为一个基本的实现,我会说你应该使用共享偏好,它使用键值来存储数据,并且很容易使用数据将保留直到你清除缓存以卸载它。

    https://pub.dev/packages/shared_preferences

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      相关资源
      最近更新 更多