Json got parsed but the cannot display the data in the UI flutter [SOLVED]

Issue

I was trying to fetch data results from a REST API and then display it in the UI. So everything went well the JSON was parsed well the try and catch method was working fine. But somehow the code was not able to display the parsed results in the UI. Neither gave me an error or exception. I have been struggling to attain the desired result for quite the past few days.

Model Class:

 import 'dart:convert';

Transaction transactionFromJson(String str) =>
    Transaction.fromJson(json.decode(str));

String transactionToJson(Transaction data) => json.encode(data.toJson());

class Transaction {
  Transaction({
    required this.dataDescription,
    required this.orderStatus,
    required this.statusObjects,
  });

  String dataDescription;
  String orderStatus;
  List<StatusObject> statusObjects;

  factory Transaction.fromJson(Map<String, dynamic> json) => Transaction(
        dataDescription: json["data-description"],
        orderStatus: json["order-status"],
        statusObjects: List<StatusObject>.from(
            json["status-objects"].map((x) => StatusObject.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "data-description": dataDescription,
        "order-status": orderStatus,
        "status-objects":
            List<dynamic>.from(statusObjects.map((x) => x.toJson())),
      };
}

class StatusObject {
  StatusObject({
    required this.type,
    required this.status,
    required this.date,
    required this.time,
  });

  String type;
  String status;
  DateTime date;
  String time;

  factory StatusObject.fromJson(Map<String, dynamic> json) => StatusObject(
        type: json["type"],
        status: json["status"],
        date: DateTime.parse(json["date"]),
        time: json["time"],
      );

  Map<String, dynamic> toJson() => {
        "type": type,
        "status": status,
        "date": date.toIso8601String(),
        "time": time,
      };
}

This is how the JSON looks like:

    {
        "data-description": "This api will return an array of objects to be placed in the order status timeline on the second screen",
        "order-status": "Success",
        "status-objects": [
            {
                "type": "Payment",
                "status": "completed",
                "date": "2021-07-02T00:00:00",
                "time": "12:00AM"
            },
            {
                "type": "Units Allocated",
                "status": "by Axis",
                "date": "2021-07-13T00:00:00",
                "time": "12:00AM"
            }
        ]
    }

API_Manager where the parsing and fetching took place Service Class

class API_Manager {
  static Future<Transaction> getDetails() async {
    var client = http.Client();
    var transactions;
    try {
      var response = await client.get(
          Uri.https("your api url here"));

      if (response.statusCode == 200) {
        var jsonString = response.body;
        var jsonMap = jsonDecode(jsonString);
        transactions = Transaction.fromJson(jsonMap);
      }
    } catch (e) {
      return transactions;
    }
    return transactions;
  }
}

The UI component where I wanted to display the parsed JSON:

Code

FutureBuilder<Transaction>(
                  future: API_Manager.getDetails(),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      var data = snapshot.data!.statusObjects;
                      return ListView.builder(
                        itemCount: data.length,
                        itemBuilder: (context, index) =>
                            Text('$index : ${data[index].status}'),
                      );
                    }
                    return Text('Something was wrong!');
                  },
                ),

The output that I am getting is "Something was wrong"

I am quite sure that I have been missing a very small piece of code to make it work. I have been working on this piece of code for quite a few days but am unable to do it. I request you, people, to please help me out in attaining the result or point out the piece of code that I have left out.

Will appreciate it if you could help me in any possible way.

Solution

try this

var response = await client
          .get(Uri.https("domain", "accounts/test-data/"));

or

var response = await http
      .get(Uri.parse("domain/accounts/test-data/"));


This one doesn’t work maybe because of the main domain part shouldn’t use /, because it indicates subPath,

      var response = await client
          .get(Uri.https("domain/accounts", "test-data/"));

Answered By – Yeasin Sheikh

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.