0
votes

There is a Dismissible widget that has a function to 'undo' the item map deletion. When I Dismiss an item that is not the last from you key on the map, it works fine, but when the item is the last item of your key it throws this error:

The method 'add' was called on null. Receiver: null Tried calling: add("Test")

This is the code:

return Dismissible(
      key: Key(event),
      child: ....my child
      onDismissed: (direction) {

        setState(() {
          _events[_thisDay].remove(event);
          if(_events[_thisDay].length == 0){
            _events.remove(_day);
          }
        });


        Scaffold.of(context).showSnackBar(SnackBar(
          content: Text(
            "Event $event dismissed !"),
          action: SnackBarAction(
            label: "Undo",
            onPressed: () => setState(() =>_events[_thisDay].add(event))), // HERE
        ));
      },
      background: Container(color: Colors.red),
    );

*How can I treat this error? _events is null. _thisDay isn't

1
First of all, in order to prevent the error you can use null check (_events[_thisDay]?.add(event)) before adding event to your list. Then, you have to check why is _events[_thisDay] null? - Ravi Singh Lodhi
Is null because there are nothing inside.. When I remove all the elements from a map it is null and doesnt accept the add method, so, how could I add on it - user14671619
Please tell me what type of key,value pair have you stored in _events? - Ravi Singh Lodhi
DateTime: String - user14671619

1 Answers

0
votes

You can check for null & then initialize _events[_thisDay] to an empty Map. Your code should look something like this:

Scaffold.of(context).showSnackBar(SnackBar(
      content: Text(
        "Event $event dismissed !"),
      action: SnackBarAction(
        label: "Undo",
        onPressed: () { 
          setState(() {
            _events[_thisDay] ??= <DateTime, String>{}; // if null, will be assigned to an empty map
            _events[_thisDay].add(event);
          });
        }),
    ));