Flutter how to save list data locally

4,301

To do this you'll certainly have to use the path_provider package with this tutorial on the flutter.dev website. You should then be able to register a file and read it at the start of your application.

Once you have imported the path_provider and the dart:io packages, you can do something like this :

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

First you get the application document directory ( the path ), then you create a File with the right path. Then if the file already exist, you read it, else you create it with the json you got and you should be good to go !

Share:
4,301
Debankush Mridha
Author by

Debankush Mridha

Updated on December 23, 2022

Comments

  • Debankush Mridha
    Debankush Mridha over 1 year

    I am building a to-do list app and I would like to store the data locally such that every time I open the app, I get all the tasks that I had created previously. I am new to flutter and this is my first app. I already tried saving the data to a file, creating a JSON file to save the data and tried using a database. Nothing seems to work. Can someone help me with this?

    This is my code: -

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

    I have 4 lists with the data. I need a simple way to save the lists such that the next time I open the app, the lists retain the data that was saved in them, the last time I had closed the app.