0

hi stackers i have a problem with returning nested data in array object using flutter, the data has shown but i cant get what i want to get i have a response like this from my backend

    "meta": {
        "code": 200,
        "status": "success",
        "message": "Data list transaksi berhasil diambil"
    },
    "data": {
        "current_page": 1,
        "data": [
            {
                "id": 1,
                "users_id": 1,
                "invoice": "INV38972",
                "seat_number": 2,
                "total_price": 1000,
                "payment_method": "TUNAI",
                "status": "PENDING",
                "items": [
                    {
                        "id": 1,
                        "menus_id": 1,
                        "transactions_id": 1,
                        "quantity": 5,
                        "menus": {
                            "id": 1,
                            "name": "Adidas NMD",
                            "price": 200,
                            "description": "Ini adalah sepatu sport",
                            "categories_id": 1,
                        }
                    }
                ]
            }
        ],
    }
}

response above is from my backend that success fully return in my response print() in flutter but i want to get the nested data in items.menus its return error Class'_InternalLinkedHashMap<String, dynamic>'has no instance getter 'menus'

for better understanding my question ill provide full model, provider and my services

this is my service getOrderList() function that i call in the futureBuilder

      var url = '$baseUrl/transaction';

      var headers = {
        'Content-type': 'application/json',
        'Authorization': 'Bearer ${userModel.token}'
      };

      var response = await http.get(Uri.parse(url), headers: headers);

      // print(response.body);
      // print('berhasil get kategori');

      if (response.statusCode == 200) {
        List data = json.decode(response.body)['data']['data'];
        List<TransactionModel> transaction = [];

        for (var item in data) {
          transaction.add(TransactionModel.fromJson(item));
        }
        // print(transaction);
        return transaction;
      } else {
        throw Exception('Gagal get Categori');
      }
    }

and this is my model code


class TransactionModel {
  int id;
  int users_id;
  String invoice;
  int seat_number;
  double total_price;
  String payment_method;
  String status;
  List items;
  // List menu;

  TransactionModel({
    this.id,
    this.users_id,
    this.invoice,
    this.seat_number,
    this.total_price,
    this.payment_method,
    this.status,
    this.items,
    // this.menu,
  });

  TransactionModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    users_id = json['users_id'];
    invoice = json['invoice'];
    seat_number = json['seat_number'];
    total_price = double.parse(json['total_price'].toString());
    payment_method = json['payment_method'];
    status = json['status'];
    items = json['items'];
    // menu = json['items']['menus'];
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'users_id': users_id,
      'invoice': invoice,
      'seat_number': seat_number,
      'items': items,
      'total_price': total_price,
      'payment_method': payment_method,
      'status': status,
      // 'menu': menu,
    };
  }
}

i already change the model data and try much method but its still not working, thats all on my code what should i do to call items.menus in result ?

1 Answer 1

2

It seems to be a problem within the model, you can use a json to dart to make model class from raw json. Keep the fetching logic as it is.

Json


            {
                "id": 1,
                "users_id": 1,
                "invoice": "INV38972",
                "seat_number": 2,
                "total_price": 1000,
                "payment_method": "TUNAI",
                "status": "PENDING",
                "items": [
                    {
                        "id": 1,
                        "menus_id": 1,
                        "transactions_id": 1,
                        "quantity": 5,
                        "menus": {
                            "id": 1,
                            "name": "Adidas NMD",
                            "price": 200,
                            "description": "Ini adalah sepatu sport",
                            "categories_id": 1
                        }
                    }
                ]
            }
  

Model class

// To parse this JSON data, do
//
//     final transactionModel = transactionModelFromMap(jsonString);

import 'dart:convert';

class TransactionModel {
    TransactionModel({
        this.id,
        this.usersId,
        this.invoice,
        this.seatNumber,
        this.totalPrice,
        this.paymentMethod,
        this.status,
        this.items,
    });

    final int id;
    final int usersId;
    final String invoice;
    final int seatNumber;
    final int totalPrice;
    final String paymentMethod;
    final String status;
    final List<Item> items;

    factory TransactionModel.fromJson(String str) => TransactionModel.fromMap(json.decode(str));

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

    factory TransactionModel.fromMap(Map<String, dynamic> json) => TransactionModel(
        id: json["id"],
        usersId: json["users_id"],
        invoice: json["invoice"],
        seatNumber: json["seat_number"],
        totalPrice: json["total_price"],
        paymentMethod: json["payment_method"],
        status: json["status"],
        items: List<Item>.from(json["items"].map((x) => Item.fromMap(x))),
    );

    Map<String, dynamic> toMap() => {
        "id": id,
        "users_id": usersId,
        "invoice": invoice,
        "seat_number": seatNumber,
        "total_price": totalPrice,
        "payment_method": paymentMethod,
        "status": status,
        "items": List<dynamic>.from(items.map((x) => x.toMap())),
    };
}

class Item {
    Item({
        this.id,
        this.menusId,
        this.transactionsId,
        this.quantity,
        this.menus,
    });

    final int id;
    final int menusId;
    final int transactionsId;
    final int quantity;
    final Menus menus;

    factory Item.fromJson(String str) => Item.fromMap(json.decode(str));

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

    factory Item.fromMap(Map<String, dynamic> json) => Item(
        id: json["id"],
        menusId: json["menus_id"],
        transactionsId: json["transactions_id"],
        quantity: json["quantity"],
        menus: Menus.fromMap(json["menus"]),
    );

    Map<String, dynamic> toMap() => {
        "id": id,
        "menus_id": menusId,
        "transactions_id": transactionsId,
        "quantity": quantity,
        "menus": menus.toMap(),
    };
}

class Menus {
    Menus({
        this.id,
        this.name,
        this.price,
        this.description,
        this.categoriesId,
    });

    final int id;
    final String name;
    final int price;
    final String description;
    final int categoriesId;

    factory Menus.fromJson(String str) => Menus.fromMap(json.decode(str));

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

    factory Menus.fromMap(Map<String, dynamic> json) => Menus(
        id: json["id"],
        name: json["name"],
        price: json["price"],
        description: json["description"],
        categoriesId: json["categories_id"],
    );

    Map<String, dynamic> toMap() => {
        "id": id,
        "name": name,
        "price": price,
        "description": description,
        "categories_id": categoriesId,
    };
}


Sign up to request clarification or add additional context in comments.

10 Comments

if i use that model, is there any work should i do in the provider? and the function in the future builder ?
No change, you can use it with the current logic you have.
its show error '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' when i print(snapshot.error) because its return null
fixed i change the model you send to me to factory TransactionModel.fromJson(Map<String, dynamic> str) => TransactionModel.fromMap(str);
how to create the factory ? i change my menus to hasMany and its return array
|

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.