0

How can I parse json array nested object to ListView in UI using Flutter?

The API response is

{
  "responseCode": "0000",
  "responseMessage": "Success",
  "date": "20200227",
  "time": "115221",
  "content": [
    {
      "postingDate": "20191203",
      "valueDate": "20191203",
      "inputDate": "20191203",
      "inputTime": "214808",
      "desc": "BUNGA JATUH TEMPO"
    },
  ]
}

Can you please help me? Thanks a lot!

3 Answers 3

2

Just check out this example where I have parsed you JSON locally :

{
    "responseCode": "0000",
    "responseMessage": "Success",
    "date": "20200227",
    "time": "115221",
    "content": [
      {
        "postingDate": "20191203",
        "valueDate": "20191203",
        "inputDate": "20191203",
        "inputTime": "214808",
        "desc": "BUNGA JATUH TEMPO",
        "noReff": "B2100000000026",
        "amount": "+20712,33",
        "balance": "+6971357445,15"
      },
      {
        "postingDate": "20191203",
        "valueDate": "20191203",
        "inputDate": "20191203",
        "inputTime": "214809",
        "desc": "BUNGA JATUH TEMPO",
        "noReff": "B2100000000033",
        "amount": "+13808,22",
        "balance": "+6971371253,37"
      }
    ]
  }

below is the model class for the json that you provided.

// To parse this JSON data, do
//
//     final myModel = myModelFromJson(jsonString);

import 'dart:convert';

MyModel myModelFromJson(String str) => MyModel.fromJson(json.decode(str));

String myModelToJson(MyModel data) => json.encode(data.toJson());

class MyModel {
    String responseCode;
    String responseMessage;
    String date;
    String time;
    List<Content> content;

    MyModel({
        this.responseCode,
        this.responseMessage,
        this.date,
        this.time,
        this.content,
    });

    factory MyModel.fromJson(Map<String, dynamic> json) => MyModel(
        responseCode: json["responseCode"],
        responseMessage: json["responseMessage"],
        date: json["date"],
        time: json["time"],
        content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "responseCode": responseCode,
        "responseMessage": responseMessage,
        "date": date,
        "time": time,
        "content": List<dynamic>.from(content.map((x) => x.toJson())),
    };
}

class Content {
    String postingDate;
    String valueDate;
    String inputDate;
    String inputTime;
    String desc;
    String noReff;
    String amount;
    String balance;

    Content({
        this.postingDate,
        this.valueDate,
        this.inputDate,
        this.inputTime,
        this.desc,
        this.noReff,
        this.amount,
        this.balance,
    });

    factory Content.fromJson(Map<String, dynamic> json) => Content(
        postingDate: json["postingDate"],
        valueDate: json["valueDate"],
        inputDate: json["inputDate"],
        inputTime: json["inputTime"],
        desc: json["desc"],
        noReff: json["noReff"],
        amount: json["amount"],
        balance: json["balance"],
    );

    Map<String, dynamic> toJson() => {
        "postingDate": postingDate,
        "valueDate": valueDate,
        "inputDate": inputDate,
        "inputTime": inputTime,
        "desc": desc,
        "noReff": noReff,
        "amount": amount,
        "balance": balance,
    };

// remove this method from the model
static Future<MyModel> getMutasiDetails(String accNumber, String startDate, String endDate) async {
  String apiURL = urlAPI";
    String username = "username";
    String password = "password";
    var bytes = utf8.encode("$username:$password");
    var credentials = base64.encode(bytes);
    var headers = {
      "Content-Type": "application/json",
      "Authorization": "Basic $credentials"
    };

  var params = Map<String, dynamic>();
  params['accNumber'] = accNumber;
  params['startDate'] = startDate;
  params['endDate'] = endDate;

  http.Response apiResult =
      await http.post(apiURL, body: params, headers: headers);
  if (apiResult.statusCode == 200) {
    return MyModel.fromJson(json.decode(apiResult.body));
  } else {
    throw Exception('failed to load data');
  }
}
}

And below is the main file where the listview gets rendered:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sample_project_for_api/model.dart';
import 'package:http/http.dart' as http;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  MyModel youModel = new MyModel();
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    getMutasiDetails("0002100000291", "", "").then((value) {
      youModel = value;
      setState(() {
        _isLoading = false;
      });
    });
  }

  Future<MyModel> getMutasiDetails(
      String accNumber, String startDate, String endDate) async {
    setState(() {
      _isLoading = true;
    });
    String apiURL = "urlAPI";
    String username = "username";
    String password = "password";
    var bytes = utf8.encode("$username:$password");
    var credentials = base64.encode(bytes);
    var headers = {
      "Content-Type": "application/json",
      "Authorization": "Basic $credentials"
    };

    var params = Map<String, dynamic>();
    params['accNumber'] = accNumber;
    params['startDate'] = startDate;
    params['endDate'] = endDate;

    http.Response apiResult =
        await http.post(apiURL, body: params, headers: headers);
    if (apiResult.statusCode == 200) {
      return myModelFromJson(apiResult.body);
    } else {
      throw Exception('failed to load data');
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _isLoading
          ? CircularProgressIndicator()
          : Container(
              child: ListView.builder(
                  itemCount: youModel.content.length,
                  itemBuilder: (context, i) {
                    return Card(
                      child: Column(
                        children: <Widget>[
                          Text(youModel.content[i].amount),
                          Text(youModel.content[i].balance),
                          Text(youModel.content[i].inputDate),
                          Text(youModel.content[i].desc),
                        ],
                      ),
                    );
                  })),
    );
  }
}


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

11 Comments

what error you are getting. can you please elaborate it properly, I am not getting you English.
just check out the changes i have made in the code and let me know.
I am run Debugging this warning: StateError (Bad state: Cannot set the body fields of a Request with content-type "application/json".)
thats because you are incorrectly setting bodyFields
i was updated code in above, please advice. thanks.
|
1

First you could take a look at this resource:

https://bezkoder.com/dart-flutter-parse-json-string-array-to-object-list/#DartFlutter_parse_complex_JSON_into_Nested_Object

It will give you a better understanding of the parsing you're trying to do.

Then take a look at this another post:

https://pusher.com/tutorials/flutter-listviews

It will give an idea of how to handle ListViews properly

1 Comment

it's already done. now, how to call array nested object in listview.
1
List<MyModel> list=[];
var requestBody = jsonEncode({'accNumber': accNumber});
http.Response response = await http.post(apiURL, body: requestBody, headers: headers);
if (response.statusCode == 200) {
  var data = json.decode(response.body);
  print(data);
  for (Map<String,dynamic> m in data['content']){
      list.add(MyModel.fromJSON(m));
      //Replace above line with your model implemtation
   }
 );
}

Comments

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.