Emir Bolat
Emir Bolat

Reputation: 1049

Dart Flutter _CastError (Null check operator used on a null value) listyukle Error

I have a code like this:

  void saveList() async {
    final prefences = await SharedPreferences.getInstance();
    prefences.setStringList("tests", prefences.getStringList("tests")! + ["English / A1 / Family / Test 1"]);
    setState(() {
    });
  }

I'm calling the saveList function somewhere. When I call it, I get an error like this:

enter image description here

_CastError (Null check operator used on a null value) saveList

It gives the error on this line:

prefences.setStringList("tests", prefences.getStringList("tests")! + ["Ingilizce / A1 / Aile / Test 1"]);

How can I solve it? Thank you for your help.

Upvotes: 0

Views: 1624

Answers (2)

Majid
Majid

Reputation: 2910

I believe your getStringList where it might be null even though you have used !. According to the documentation

// Try reading data from the 'items' key. If it doesn't exist, returns null.
final List<String>? items = prefs.getStringList('items');

Thus, you can change your code in order to make sure the value is never null but it's an array even though it will be empty. Your example will be


  void saveList() async {
    final prefences = await SharedPreferences.getInstance();

    final existingValues =
        prefences.getStringList("tests") ?? []; // always a List

    prefences.setStringList(
      "tests",
      [...existingValues, "English / A1 / Family / Test 1"],
    );

    setState(() {});
  }


Upvotes: 1

Kantine
Kantine

Reputation: 771

I think the first time you call this line, "tests" has never been set before in prefences, then prefences.getStringList("tests") is null.

Try this to fix it:

  void saveList() async {
    final prefences = await SharedPreferences.getInstance();
    List<String> previousList = prefences.getStringList("tests") ?? [];
    prefences.setStringList("tests", previousList + ["English / A1 / Family / Test 1"]);
    setState(() {
    });
  }

Upvotes: 1

Related Questions