颤振如何在本地保存列表数据

时间:2020-08-06 09:03:27

标签: json database file flutter dart

我正在构建一个待办事项列表应用程序,我想将数据存储在本地,以便每次打开该应用程序时,我都能获得之前创建的所有任务。我是新手,这是我的第一个应用程序。我已经尝试将数据保存到文件中,创建一个JSON文件来保存数据,并尝试使用数据库。似乎没有任何作用。有人可以帮我吗?

这是我的代码:-

import 'package:flutter/material.dart';

class toDoList extends StatefulWidget
{
    bool data = false;
    @override
    createState() 
    {
        return new toDoListState();
    }
}

class toDoListState extends State<toDoList>
{
  List<String> tasks = [];
  List<bool> completedTasks = [];
  List<String> descriptions = [];
  List<bool> importance = [];


    @override
    Widget build(BuildContext context)
    {
        return new Scaffold
        (
            body: buildToDoList(),
            floatingActionButton: new FloatingActionButton
            (
                onPressed: addToDoItemScreen, 
                tooltip: 'Add Task',
                child: new Icon(Icons.add),
            ),
        );
    }

    Widget buildToDoList()
    {
        return new ListView.builder
        (
            itemBuilder: (context, index)
            {
                if(index < tasks.length)
                {
                  if(tasks[index] == "#45jiodg{}}{OHU&IEB")
                  {
                    tasks.removeAt(index);
                    descriptions.removeAt(index);
                    importance.removeAt(index);
                  } 
                    return row(tasks[index], descriptions[index], index);
                };
            },
        );
    }

    Widget row(String task, String description, int index)
    {                  
        return Dismissible(
        key: UniqueKey(),
        background: Container(color: Colors.red, child: Align(alignment: Alignment.center, child: Text('DELETE', textAlign: TextAlign.center, style: TextStyle(color: Colors.white, fontSize: 18),))),
        direction: DismissDirection.horizontal,
        onDismissed: (direction) {
        setState(() {
          tasks.removeAt(index);
          if(completedTasks[index])
          {
              completedTasks.removeAt(index);
          }
          descriptions.removeAt(index);
          importance.removeAt(index);
        });
          Scaffold.of(context).showSnackBar(SnackBar(content: Text(task+" dismissed")));
        },
        child: CheckboxListTile(
          controlAffinity: ListTileControlAffinity.leading,
          title: Text(task, style: (completedTasks[index]) ? TextStyle(decoration: TextDecoration.lineThrough) : TextStyle(),),
          subtitle: Text(descriptions[index], style: (completedTasks[index]) ? TextStyle(decoration: TextDecoration.lineThrough) : TextStyle(),),
          isThreeLine: true,
          secondary: (importance[index])? Icon(Icons.error, color: Colors.red,) : Text(''),
          value: completedTasks[index],
          onChanged: (bool value) {
           setState(() {
              if(completedTasks[index])
              {
                  completedTasks[index] = false;
              }
              else
              {
                  completedTasks[index] = true;
              }
           });
          },
        ));
    }
  
  void addToDoItemScreen() {
    int index = tasks.length;
    while (importance.length > tasks.length) {
      importance.removeLast();
    }
    importance.add(false);
    tasks.add("#45jiodg{}}{OHU&IEB");
    descriptions.add("No Description");
    completedTasks.add(false);
    
    Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
      return StatefulBuilder(builder: (context, setState) { // this is new
                return new Scaffold(
                    appBar: new AppBar(title: new Text('Add a new task')),
                    body: Form(
                      child: Column(
                        children: <Widget>[
                          TextField(
                            autofocus: true,
                            onSubmitted: (name) {
                              addToDoItem(name);
                              //Navigator.pop(context); // Close the add todo screen
                            },
                            decoration: new InputDecoration(
                                hintText: 'Enter something to do...',
                                contentPadding: const EdgeInsets.all(20.0),
                                border: OutlineInputBorder()),
                          ),
                          TextField(
                            //autofocus: true,
                            //enabled: descriptions.length > desc,
                            onSubmitted: (val) {
                              addDescription(val, index);
                            },
                            decoration: new InputDecoration(
                                hintText: 'Enter a task decription...',
                                contentPadding: const EdgeInsets.all(20.0),
                                border: OutlineInputBorder()),
                          ),
                          Row(
                            children: <Widget> [
                              Switch(
                              value: importance[index],
                              onChanged: (val) {
                                setState(() {
                                });
                                impTask(index);
                              },
                            ),
                            Text('Important Task', style: TextStyle(fontSize: 18)),
                            ],
                          ),
                  RaisedButton(onPressed: () { Navigator.pop(context); }, child: Text('DONE', style: TextStyle(fontSize: 20)),)
                ],
              ),
            ));
      });
    }));
  }

    void addToDoItem(String task)
    {
        setState(() {
          tasks.last = task;
        });
    }

    void addDescription(String desc, int index)
    {
        setState(() {
          descriptions.last = desc;
        });
    }

    void impTask(int index)
    {
        setState(() {
          if(importance[index])
          {
            importance[index] = false;
          }
          else 
          {
            importance[index] = true;
          }
        });
    }

    
}

我有4个包含数据的列表。我需要一种简单的方法来保存列表,以便下次打开应用程序时,列表会保留上次关闭应用程序时保存在其中的数据。

1 个答案:

答案 0 :(得分:1)

为此,您肯定必须在flutter.dev网站上将path_provider软件包与this教程一起使用。然后,您应该能够注册文件并在应用程序的开头读取它。

一旦导入了path_provider和dart:io包,就可以执行以下操作:

 final directory = await getApplicationDocumentsDirectory();
    final File file = File('${directory.path}/jsonObjects.json');
    if (await file.exists()) {
      json = await file.readAsString();
    } else {
      file.writeAsString(json);
    }

首先获得应用程序文档目录(path),然后创建具有正确路径的File。然后,如果该文件已经存在,请阅读该文件,否则使用获得的json创建该文件,应该一切顺利!