0

I want to store and read details using local storage. I have added dependencies in the pubspec.yaml file and imported the shared_preferences class.

Hint showed to add late before SharedPreferences prefs; after adding late, app doesn't store data.

import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Body extends StatefulWidget {
  const Body({Key? key}) : super(key: key);

  @override
  State<Body> createState() => _BodyState();
}

class _BodyState extends State<Body> {
  SharedPreferences prefs;
  List todos = [];

  setupTodo() async {
    prefs = await SharedPreferences.getInstance();
    String? stringTodo = prefs.getString('todo');
    List todoList = jsonDecode(stringTodo!);
    for (var todo in todoList) {
      setState(() {
        todos.add(todo().fromJson(todo));
      });
    }
  }

  void saveTodo() async {
    prefs = await SharedPreferences.getInstance();
    List items = todos.map((e) => e.toJson()).toList();
    prefs.setString('todo', jsonEncode(items));
  }
OMi Shah
  • 5,768
  • 3
  • 25
  • 34
  • Possible duplicate questions: 1.) https://stackoverflow.com/questions/69359360/flutter-sharedpreferences-non-nullable-instance-fields 2.) https://stackoverflow.com/questions/68233927/the-non-nullable-variable-preferences-must-be-initialized-try-adding-an-init 3.) https://stackoverflow.com/questions/72529568/how-to-initialize-sharedpreferences-flutter 4.) https://stackoverflow.com/questions/70055345/shared-preferences-must-be-initialized-error – OMi Shah Aug 25 '23 at 16:46

1 Answers1

0
setupTodo() async {
    // do not initial your pref, unless you create the util class or make your own module

    var prefs = await SharedPreferences.getInstance();
    //make prefs variable for each class
    String? stringTodo = prefs.getString('todo');
    List todoList = jsonDecode(stringTodo!);
    for (var todo in todoList) {
      setState(() {
        todos.add(todo().fromJson(todo));
      });
    }
  }