Home > Software engineering >  How to properly record local storage(sharedpreferences) for a list(todolist)
How to properly record local storage(sharedpreferences) for a list(todolist)

Time:10-28

I am new to flutter. I have a task to create a local repository for a task list. I tried many options to write the code but none of them worked. I read and watched a lot of videos and articles. Please write your options how I can record it

Here is my code:

import 'dart:convert';
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:shared_preferences/shared_preferences.dart';


class Home extends StatefulWidget {
 const Home ({key}): super(key: key);

  @override
  State<Home> createState() => _HomeState();
}
  class _HomeState extends State<Home> {

  final myController = TextEditingController();
  bool submit = false;

  Color mainColor = Color(0xFFEEEFF5);
  Color secColor = Color(0xFF3A3A3A);
  Color tdBlue = Color(0xFF5F52EE);


String temp = "";
  List todoList = [];

  @override
  void initState() {

    super.initState();

    myController.addListener(() {
      setState(() {
        submit = myController.text.isNotEmpty;
      });
    });

      todoList.addAll(['Biy milk','Dishhh Wash','Придбати картоплю', 'Buy cucumbers', 'Kylunuch'],);
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  void clearText() {
      myController.clear();
  }

     @override
  Widget build(BuildContext context){
   return Scaffold(
      backgroundColor: mainColor,
     appBar: AppBar(
       elevation: 0.0,
       backgroundColor: secColor,
      title: Text ('ToDo - List', style: TextStyle(fontSize: 26.5, fontWeight: FontWeight.bold, fontStyle: FontStyle.italic),),
     ),
        body: Column(
          children: [
            Container(

              margin: EdgeInsets.only(
                top: 15.0,
                left: 13.0,
                right: 8.0,
              ),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      onChanged: (String value) {
                        temp = value;
                      },

                      controller: myController,
                      decoration:
                      InputDecoration(
                          prefixIcon: Icon(Icons.notes, color: Colors.orangeAccent,),
                          labelText: 'Замітка',
                          hintText: 'Введіть замітку',
                          filled: true,
                          fillColor: Colors.white,
                          border: OutlineInputBorder(),
                          contentPadding: EdgeInsets.all(10.0),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(30.0),),
                          ),
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 10.0,
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(backgroundColor: tdBlue),

                    onPressed:
                    submit ? () => submitData() : null,
                    child:
                    Text(' ', style: TextStyle(fontSize: 35),),
                  ),
                ], // Закривається 2-ий чілдрен
              ), //Row 1-ий
            ),

            Expanded(
              child: Padding(
                padding: EdgeInsets.only(
                  top: 15.0,
                ),
                child: ListView.builder(
                    itemCount: todoList.length,
                    itemBuilder: (BuildContext context, int index){
                      return Dismissible(
                        key: Key(todoList[index]),
                        child: Card(
                          margin: EdgeInsets.only(
                            top: 16.0,
                            left: 25.0,
                            right: 25.0,
                          ),
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25.0)),
                          elevation: 0.0,
                          child:
                          ListTile(
                            leading: Icon(Icons.delete_sweep, color: Colors.orangeAccent,),
                            title: Text(todoList[index],
                            ),),

                        ),
                        onDismissed: (direction){
                          if (direction == DismissDirection.endToStart) {
                            setState(() {
                              todoList.removeAt(index);
                            });// Закривається Сетстейт (")") і }
                          }
                        }, // Закривається ОнДісмісед
                      );
                    },
                ),
              )

            ),

          ], // Закривається 1-ий чілдрен
        ),
   );
  }
  submitData()  {

    setState(() {

      todoList.add(temp);
      clearText();

    });
  } // submit data
}

I tried many options to write the code but none of them worked.

CodePudding user response:

Try this

  List<String> todoList = [];

  @override
  void initState() {
    super.initState();
    myController.addListener(() {
      setState(() {
        submit = myController.text.isNotEmpty;
      });
    });
    omLoadData();
  }

  submitData() async {
    setState(() {
      todoList.add(temp);
      clearText();
    });
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setStringList('todo_list', todoList);
  }

  omLoadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final data = prefs.getStringList("todo_list");
    todoList.addAll(data!);
  }
  • Related