Json got parsed but the cannot display the data in the UI flutter

221

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/"));
Share:
221
Pratyay Sinha
Author by

Pratyay Sinha

Updated on December 31, 2022

Comments

  • Pratyay Sinha
    Pratyay Sinha over 1 year

    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.

    • John Joe
      John Joe almost 3 years
      print out response.body. What value you get?
    • Pratyay Sinha
      Pratyay Sinha almost 3 years
      Yeah I am getting the json output
    • John Joe
      John Joe almost 3 years
      what statusCode you got?
    • Pratyay Sinha
      Pratyay Sinha almost 3 years
      Hey! I have updated the code. Also, I am quite new to integrating REST APIs in the code. So I request if you can then please help me code this problem out @JohnJoe
    • John Joe
      John Joe almost 3 years
      The first thing we need to know is whether the if block get executed. Please print out the response.statusCode. What value you get?
    • Pratyay Sinha
      Pratyay Sinha almost 3 years
      No the if block did not got executed. Neither I got any output
    • John Joe
      John Joe almost 3 years
    • Yeasin Sheikh
      Yeasin Sheikh almost 3 years
      you are missing to select the key status-objects, can you provide Transaction calss so I can test easily ?
    • Pratyay Sinha
      Pratyay Sinha almost 3 years
      Please check @YeasinSheikh I have added the Transaction class.
    • Pratyay Sinha
      Pratyay Sinha almost 3 years
      Also if you want I have also attached the API
    • John Joe
      John Joe almost 3 years
      tried this Uri.https("https://api.skidfintech.com/accounts/test-data/")‌​);
    • Pratyay Sinha
      Pratyay Sinha almost 3 years
      This is not working in my case
    • Pratyay Sinha
      Pratyay Sinha almost 3 years
      Hey!! Would appreciate if you could just have a look at this problem that I am facing stackoverflow.com/questions/68603763/…
  • Pratyay Sinha
    Pratyay Sinha almost 3 years
    Although I got the response body in a print statement. But I am still struggling to get the response to the UI. Kindly can you look at the mistake I am running into
  • Yeasin Sheikh
    Yeasin Sheikh almost 3 years
    I'm not getting the UI problem, can you share it. may be you can try on 'FutureBuilder' ``` if (snapshot.connectionState == ConnectionState.waiting) return CircularProgressIndicator(); if (snapshot.hasData) { ......... ``` then
  • Pratyay Sinha
    Pratyay Sinha almost 3 years
    Hey!! Would appreciate if you could remove the API URL from the solution.
  • Pratyay Sinha
    Pratyay Sinha almost 3 years
    Hey!! Would appreciate if you could just have a look at this problem that I am facing stackoverflow.com/questions/68603763/…
  • Pratyay Sinha
    Pratyay Sinha over 2 years
    Hey!! Can you help me solve a problem? stackoverflow.com/questions/68863386/…