flutterflutter-sharedpreference

Non-nullable instance of SharedPreferences must be initialized in Flutter


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

Solution

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