Uncaught (in promise) Error: Expected a value of type 'List<dynamic>', but got one of type '_JsonMap'

Issue

I am new to flutter. Am trying to consume a Rest_Api from my UI to make a get Request,however i am getting an error "Expected a value of type ‘List’, but got one of type ‘_JsonMap’",which have tried to debug based on the suggestions found online but I can’t seem to solve this issue. Here is a screenshot of the error am getting:
enter image description here

Here is my model and service classes:

import 'package:json_annotation/json_annotation.dart';
part 'unit.g.dart';

@JsonSerializable(explicitToJson: true)
class Unit {
  String ? id;
  String name;
  String baseUnit;
  var baseValue;

  Unit({
    this.id,
    required this.name,
    required this.baseUnit,
    required this.baseValue,
  });
  factory Unit.fromJson(Map < String, dynamic > json) => _$UnitFromJson(json);
  Map < String, dynamic > toJson() => _$UnitToJson(this);
}
Future < List < Unit >> search(searchText, page) async {
  var searchUrl = "${ApiEndPoint.baseUrl}/unit?q=$searchText&page=$page";
  var response = await http.get(
    Uri.parse(searchUrl),
    headers: {
      "Content-Type": "application/json"
    },
  );
  var units = convert.json.decode(response.body) as List;
  List < Unit > unitList = [];
  unitList = units.map((i) => Unit.fromJson(i)).toList();
  // print(unitList.length);
  // print(response.body);
  return unitList;
}

Serialized Model Class is;

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'unit.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Unit _$UnitFromJson(Map < String, dynamic > json) {
  return Unit(
    id: json['id'] as String ? ,
    name : json['name'] as String,
    baseUnit: json['baseUnit'] as String,
    baseValue: json['baseValue'],
  );
}

Map < String, dynamic > _$UnitToJson(Unit instance) => < String, dynamic > {
  'id': instance.id,
  'name': instance.name,
  'baseUnit': instance.baseUnit,
  'baseValue': instance.baseValue,
};

What could I be doing wrong?

Solution

I had to change to change the return value in the service to this and somehow it worked.

Future < List < UnitSearch >> search(searchText, page) async {
  var searchUrl = "${ApiEndPoint.baseUrl}/unit?q=$searchText&page=$page";
  http.Response response = await http.get(
    Uri.parse(searchUrl),
    headers: {
      "Content-Type": "application/json"
    },
  );
  final data = json.decode(response.body);
  return List < UnitSearch > .from(
    data['units'].map((item) => UnitSearch.fromJson(item)));
}

Answered By – Emmon

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *