How to show list in flutter

Issue

Hello i want to ask how to show list in flutter

this is aan example response from json, it have another list inside

{
"results": [
    {
        "pembelian": [
            {
                "foto": null,
                "note": null,
                "avail": 1,
                "harga": 5500,
                "id_toko": 112,
                "id_barang": 415,
                "harga_toko": 4400,
                "nama_barang": "Nasi"
            },
            {
                "foto": null,
                "note": null,
                "avail": 1,
                "harga": 5500,
                "id_toko": 112,
                "id_barang": 414,
                "harga_toko": 4400,
                "nama_barang": "Air"
            }
        ],
        "payment_method": "cash",
        "total_harga": 17750
    }
        ]
}

this is how i take it from API

class PesananApi {

  static const String api = 'https://api.api.id/';
  static const String apiOver = 'inv?invoice=';


  Future<Invoice> getListInv({@required String invoice}) async {
    final String url = api + apiOver + invoice;
    print(url);
    var response = await http.get(url).then((val) => json.decode(val.body));

    return Invoice.fromJson(response['results']);

  }
}

and this how i show it

FutureBuilder<Invoice>(
                            future: PesananApi().getListInv(
                                invoice:
                                    snapshot.data.data['invoiceId'].toString()),
                            builder: (context, data) {
                              if (!data.hasData)
                                return Center(
                                  child: CircularProgressIndicator(),
                                );
                              return ListView.builder(
                                itemCount: data.data.pembelian.length,
                                itemBuilder: (context, i) => new
                                Text(data.data.pembelian[i].namaBarang),
                              );
                            }),

for the invoice class you can see from here
https://app.quicktype.io?share=8uxohFwef3SQwLcMTsdy

i only want to whow list from pembelian

does anyone know whats wrong with this code ? thanks

Solution

You have to change this line from:

return Invoice.fromJson(response['results']);

to:

return Invoice.fromJson(response['results'][0]);

I have made a working example here:

import 'package:flutter/material.dart';
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  static const routeName = '/';

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<Invoice>(
          future: PesananApi().getListInv(invoice: "abc"),
          builder: (context, data) {
            if (!data.hasData)
              return Center(
                child: CircularProgressIndicator(),
              );
            return ListView.builder(
              itemCount: data.data.pembelian.length,
              itemBuilder: (context, i) =>
                  new Text(data.data.pembelian[i].namaBarang),
            );
          }),
    );
  }
}

class PesananApi {
  static const String api = 'https://api.api.id/';
  static const String apiOver = 'inv?invoice=';

  static const body = """{
"results": [
    {
        "pembelian": [
            {
                "foto": null,
                "note": null,
                "avail": 1,
                "harga": 5500,
                "id_toko": 112,
                "id_barang": 415,
                "harga_toko": 4400,
                "nama_barang": "Nasi"
            },
            {
                "foto": null,
                "note": null,
                "avail": 1,
                "harga": 5500,
                "id_toko": 112,
                "id_barang": 414,
                "harga_toko": 4400,
                "nama_barang": "Air"
            }
        ],
        "payment_method": "cash",
        "total_harga": 17750
    }
        ]
}""";

  Future<Invoice> getListInv({@required String invoice}) async {
    final String url = api + apiOver + invoice;
    print(url);

    // replaced http call with static result
    //var response = await http.get(url).then((val) => json.decode(val.body));
    var response = json.decode(body);

    // replace response['results'] with response['results'][0]
    return Invoice.fromJson(response['results'][0]);
  }
}

class Invoice {
  List<Pembelian> pembelian;
  String paymentMethod;
  int totalHarga;

  Invoice({
    this.pembelian,
    this.paymentMethod,
    this.totalHarga,
  });

  factory Invoice.fromJson(Map<String, dynamic> json) => Invoice(
        pembelian: List<Pembelian>.from(
            json["pembelian"].map((x) => Pembelian.fromJson(x))),
        paymentMethod: json["payment_method"],
        totalHarga: json["total_harga"],
      );

  Map<String, dynamic> toJson() => {
        "pembelian": List<dynamic>.from(pembelian.map((x) => x.toJson())),
        "payment_method": paymentMethod,
        "total_harga": totalHarga,
      };
}

class Pembelian {
  dynamic foto;
  dynamic note;
  int avail;
  int harga;
  int idToko;
  int idBarang;
  int hargaToko;
  String namaBarang;

  Pembelian({
    this.foto,
    this.note,
    this.avail,
    this.harga,
    this.idToko,
    this.idBarang,
    this.hargaToko,
    this.namaBarang,
  });

  factory Pembelian.fromJson(Map<String, dynamic> json) => Pembelian(
        foto: json["foto"],
        note: json["note"],
        avail: json["avail"],
        harga: json["harga"],
        idToko: json["id_toko"],
        idBarang: json["id_barang"],
        hargaToko: json["harga_toko"],
        namaBarang: json["nama_barang"],
      );

  Map<String, dynamic> toJson() => {
        "foto": foto,
        "note": note,
        "avail": avail,
        "harga": harga,
        "id_toko": idToko,
        "id_barang": idBarang,
        "harga_toko": hargaToko,
        "nama_barang": namaBarang,
      };
}

Answered By – camillo777

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published