flutter - 关闭Flutter应用程序后如何保存数据?

标签 flutter dart state-management

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

最佳答案

只需查看我创建的此示例待办事项列表代码即可。

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

让我知道是否可行

关于flutter - 关闭Flutter应用程序后如何保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62642079/

相关文章:

angular5 - Angular 6 - 为什么使用 @ngrx/store 而不是服务注入(inject)

c++ - 我可以将 C++ 代码(或用 C++ 编写的库)与混合移动应用程序代码混合使用吗?

linux - -bash : $: command not found when installing Dart package

android - 如何将现有的sqlite数据库添加到Flutter并作为卡片列表打印?

dart - Flutter 在 native 应用程序中打开本地 Assets (PDF)

vue.js - 数据全部存储在vuex好还是redux好?

flutter - 提供程序对象请求在现有构建过程中进行重建

flutter - 应用程序终止时是否可以运行代码?

flutter - Flutter将数据传递给Statefulwidget

flutter - 如何在flutter中设置App Bar底部的标题和副标题