3

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.

1
  • instead of forcing typecast, it will be better to accept null value Commented Aug 23, 2022 at 5:01

1 Answer 1

1

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>[];
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.