skip to Main Content

I build an app to read data through an api and I am trying to retrive data from api put i have this error :

I made a model class for the Users (Character):

class Character {
  late int id;
  late String name;
  late String status;
  late String species;
  late String type;
  late String gender;
  late List<dynamic> origin;
  late List<dynamic> location;
  late String image;
  late List<dynamic> episode;

  Character.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    status = json['status'];
    species = json['species'];
    type = json['type'];
    gender = json['gender'];
    origin = json['origin'];
    location = json['location'];
    image = json['image'];
    episode = json['episode'];
  }
}

this is the repository to read the json into widget :

import 'package:study_bloc/data/web_services/character_api.dart';

import '../models/characters.dart';

class CharactersRepository {
  final CharactersWebServices charactersWebServices;

  CharactersRepository(this.charactersWebServices);

  Future<List<Character>> getAllCharacters() async {
    final characters = await charactersWebServices.getAllCharacters();
    return characters
        .map((character) => Character.fromJson(character))
        .toList();
  }
}

This is the JSON information i’m trying to read although its only a small part of it:

"results": [
        {
            "id": 1,
            "name": "Rick Sanchez",
            "status": "Alive",
            "species": "Human",
            "type": "",
            "gender": "Male",
            "origin": {
                "name": "Earth (C-137)",
                "url": "https://rickandmortyapi.com/api/location/1"
            },
            "location": {
                "name": "Citadel of Ricks",
                "url": "https://rickandmortyapi.com/api/location/3"
            },
            "image": "https://rickandmortyapi.com/api/character/avatar/1.jpeg",
            "episode": [
                "https://rickandmortyapi.com/api/episode/1",
                "https://rickandmortyapi.com/api/episode/2",
                "https://rickandmortyapi.com/api/episode/3",
                "https://rickandmortyapi.com/api/episode/4",
            ],
        },

The error i am currently running into is :

 type '_Map<String, dynamic>' is not a subtype of type 'FutureOr<List<dynamic>>'

this is the Web Api :

import 'package:dio/dio.dart';
import 'package:study_bloc/constant/strings.dart';

class CharactersWebServices {
  late Dio dio;

  CharactersWebServices() {
    BaseOptions options = BaseOptions(
      baseUrl: baseUrl,
      receiveDataWhenStatusError: true,
      connectTimeout: const Duration(seconds: 20),
      receiveTimeout: const Duration(seconds: 20),
    );

    dio = Dio(options);
  }
  Future<List<dynamic>> getAllCharacters() async {
    try {
      Response response = await dio.get('character');
      print(response.data.toString());
      return response.data;
    } catch (e) {
      print(e.toString());
      return [];
    }
  }
}

How do i rectify this error?

2

Answers


  1. Its because the response is map not a list.

    Try adding this.

    return character.fromJson(json.decode(response.body))`
    
    Login or Signup to reply.
  2. The DIO response data property is a Map<String, dynamic> as indicated by the error message and you are trying to cast it into List<dynamic>. This is expected as you indicate it should be a JSON style of data.

    In addition, the characters data is contained within the field ‘results’ of that data object.

    class CharactersRepository {
      final CharactersWebServices charactersWebServices;
    
      CharactersRepository(this.charactersWebServices);
    
      Future<List<Character>> getAllCharacters() async {
        final characters = await charactersWebServices.getAllCharacters();
        return characters
            .map<Character>((character) => Character.fromJson(character as Map<String, dynamic>))
            .toList();
      }
    
    Future<List<dynamic>> getAllCharacters() async {
        try {
          Response response = await dio.get('character');
          final Map<String, dynamic> json = response.data as Map<String, dynamic>;
          return json['results'] as List<dynamic>;
        } catch (e) {
          print(e.toString());
          return [];
        }
      }
    

    You should also handle the exception shomehow, probably throw a FormatException.

    I would recommend you to have a linter in your project, like flutter_lints

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search