Home > Mobile >  A value of type 'List<dynamic>' can't be assigned to a variable of type 'L
A value of type 'List<dynamic>' can't be assigned to a variable of type 'L

Time:08-24

im new in flutter , and i want to display my data from api json to my app with ResteApi , i made a model like that :

 class Todo {
  final int id;
  final String title;
  final bool completed;

  Todo({required this.id, required this.title, required this.completed});

  factory Todo.fromJson(Map<String, dynamic> json) {
    return Todo(
        id: json["id"] as int,
        title: json["title"] as String,
        completed: json["completed"] as bool);
  }
  Map<String, dynamic> toJson() => {'title': title, 'completed': completed};

  @override 
  String toString() {
    return 'Todo{id: $id, title: $title, completed: $completed}';
  }
}

And a methode get in service class Like that :

final String apiUrl = "https://jsonplaceholder.typicode.com/todos";

  
  Future<List<Todo>> getCases() async {
    Response res = await get(Uri.parse(apiUrl));

    if (res.statusCode == 200) {
      List<dynamic> body = jsonDecode(res.body);
      List<Todo> todo = body.map((dynamic item) => todo.fromJson(item)).toList();
      return todo;
    } else {
      throw "Failed to load cases list";
    }
  }

but this errors it display to me:

A value of type 'List<dynamic>' can't be assigned to a variable of type 'List<Todo>'.
Try changing the type of the variable, or casting the right-hand type to 'List<Todo>'

how can i fix it

CodePudding user response:

There is a typo todo.fromJson, it will be Todo.fromJson

List<Todo> todo = body.map((dynamic item) => Todo.fromJson(item)).toList();

Also it is better to accept null data

    List<dynamic>? body = jsonDecode(res.body);
    final todo =
        body?.map((dynamic item) => Todo.fromJson(item)).toList() ?? [];
    return todo;

CodePudding user response:

Try this:

  if (res.statusCode == 200) {
      List<dynamic> body = jsonDecode(res.body);
      List<Todo> todo = body.map<Todo>((item) => Todo.fromJson(item)).toList();
      return todo;
    } else {
      throw "Failed to load cases list";
    }

CodePudding user response:

// create function like this inside ApiFunctionsCall() class
Future<String?> dataListApiCalls() async {
  try {
    final result = await InternetAddress.lookup('google.com');
    if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
      final response = await http.get(Uri.parse('url_of_api'));
      if (response.statusCode == 200) {
        //print(response.body);
        return response.body;
      }
    } else {
      print("check internet connection");
    }
  } catch (e) {
    print(e);
  }
}

//then in call function other file

// create list
List<Todo> searchDataList = [];

// other function
void getDataList() async {
  final response = await ApiFunctionsCall().dataListApiCalls();
  final searchModalDataClass = jsonDecode(response!);
  setState(() {
    for (var i = 0; i < searchModalDataClass.data.length; i  ) {
      Todo todo = Todo(
          id: searchModalDataClass.data[i].id,
          email: searchModalDataClass.data[i].email,
      searchDataList.add(todo);
    }
  });
}
  • Related