Home > front end >  How do I map a JSON map of list of map from API for HTTP get request
How do I map a JSON map of list of map from API for HTTP get request

Time:09-26

I keep getting this error:

NoSuchMethodError (NoSuchMethodError: The method 'map' was called on null. Receiver: null Tried calling: map(Closure: (dynamic) => Name1Name2))

I am trying very hard to solve this error. I am certain I am not mapping the data properly.

My fake REST API from which I'm fetching and sending the data to

"messagesBetweenTwoUsers": {
    "Name1Name2": [
      {
        "senderName": "John",
        "message": "How are you doing?"
      }
    ]
  }

This is my get messages file

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'messages_model.dart';

Future<List<MessageModel>> getMessages() async {
  try {
    var getResponse = await http.get(
      Uri.parse("http://127.0.0.1:3000/messagesBetweenTwoUsers"),
    );

    if (getResponse.statusCode == 200) {
     
      String getData = getResponse.body;

      var jsonData =
          jsonDecode(getData);

      var getResult = jsonData["Name1Name2"].map(
        (e) => Name1Name2.fromJson(e),
      );


//here it throws me an error, in getResult, right when I am using map()
//NoSuchMethodError (NoSuchMethodError: The method 'map' was called on null.
//Receiver: null
//Tried calling: map(Closure: (dynamic) => Name1Name2))


      return getResult; 
    } else {
      return [];
    }
  } catch (error) {
    debugPrint("ERROR IN FETCHING FROM GET-MESSAGE-API: $error");
  }
  return [];
}

My model class


import 'package:meta/meta.dart';
import 'dart:convert';

class MessageModel {
    MessageModel({
        required this.name1Name2,
    });

    final List<Name1Name2> name1Name2;

    factory MessageModel.fromRawJson(String str) => MessageModel.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory MessageModel.fromJson(Map<String, dynamic> json) => MessageModel(
        name1Name2: List<Name1Name2>.from(json["name1name2"].map((x) => Name1Name2.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "name1name2": List<dynamic>.from(name1Name2.map((x) => x.toJson())),
    };
}

class Name1Name2 {
    Name1Name2({
        required this.senderName,
        required this.message,
    });

    final String senderName;
    final String message;

    factory Name1Name2.fromRawJson(String str) => Name1Name2.fromJson(json.decode(str));

    String toRawJson() => json.encode(toJson());

    factory Name1Name2.fromJson(Map<String, dynamic> json) => Name1Name2(
        senderName: json["senderName"],
        message: json["message"],
    );

    Map<String, dynamic> toJson() => {
        "senderName": senderName,
        "message": message,
    };
}

CodePudding user response:

You need to learn https://app.quicktype.io/

  1. As you are looking/decoding the json is not right, so the following website will help you do it - quicktype. I highly encourage you to explore the website with different options.

  2. As @Mayo Win said. You do need to learn Null Safety feature. Otherwise it make your code prone to error.

  3. From your method getMessages() just call the following -

CustomDataModel customDataModel = customDataModelFromJson(response.bodyString ?? '');
  • Related