Home > Mobile >  Unhandled Exception: type 'Null' is not a subtype of type 'List<dynamic>'
Unhandled Exception: type 'Null' is not a subtype of type 'List<dynamic>'

Time:08-24

Objective is to convert a String to List using map and return the value to a function call.

I am using SharedPreferences to save a list of object called where in I save the data at a point and get the data when it is to be put on view.

The below block is the function where the error is occurring.

void getData() async {
    final prefs = await SharedPreferences.getInstance();
    final String taskString = prefs.getString('task_data').toString();
    List<Task> tasksData = Task.decode(taskString);
    _tasks = tasksData;
    notifyListeners();
  }

decode() looks basically does the conversion.

static List<Task> decode(String tasks) {
    return (jsonDecode(tasks) as List<dynamic>).map<Task>((task) {
      return Task.fromJson(task);
    }).toList();

It advises to check for null condition in type cast of decode(). But on performing the check, it gives the same error.

CodePudding user response:

your response might be not a proper map so it cannot decode that data using the jsonDecode function so it returns Null, so you can use your function like this might be helpful for you :

static List<Task> decode(String tasks) {
  var data = (jsonDecode(tasks) as List<dynamic>?);
  if(data != null){
    return (jsonDecode(tasks) as List<dynamic>?)!.map<Task>((task) {
      return Task.fromJson(task);
    }).toList();
  } else {
    return <Task>[];
  }
}
  • Related