0

I have trouble displaying data, all data is received correctly from the Get method, but I can not handle it to show values.

In the getDataLadder successfully received data in response.body and I can see result with print('Response Body : ${response.body}');

With this section I store data in stringResponse value, but I can't show json data in this section:

Widget getBody() {
    var size = MediaQuery.of(context).size;
    return Container(
      width: size.width,
      height: size.height,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(10),
              bottomRight: Radius.circular(10)),
          color: Colors.white),
      child: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(
              height: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Flexible(
                  child: Container(
                    height: 1,
                    decoration:
                        BoxDecoration(color: Colors.grey.withOpacity(0.2)),
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
                Text(
                  stringResponse.toString(),
                  style: TextStyle(color: Colors.black54),
                ),
                SizedBox(
                  width: 10,
                ),
                Flexible(
                  child: Container(
                    height: 1,
                    decoration:
                        BoxDecoration(color: Colors.grey.withOpacity(0.2)),
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 15,
            ),
            Column(
                children: List.generate(nardeban_data.length, (index) {
              return Column(
                children: [
                  Padding(
                      padding: const EdgeInsets.only(right: 5, left: 5),
                      child: Container(
                        decoration: new BoxDecoration(
                          image: new DecorationImage(
                            image: new AssetImage("assets/images/bg.png"),
                            fit: BoxFit.fill,
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              height: 90,
                              // width: (size.width - 20) * 0.68,
                              child: Row(
                                children: [
                                  SizedBox(width: 20), // give it width
                                  Container(
                                      width: 40,
                                      decoration: BoxDecoration(
                                          color: Colors.blue,
                                          border:
                                              Border.all(color: Colors.blue),
                                          borderRadius:
                                              BorderRadius.circular(40.0)),
                                      child: Padding(
                                          padding: EdgeInsets.all(10.0),
                                          child: Text("14",
                                              style: TextStyle(
                                                  fontSize: 13.0,
                                                  fontWeight: FontWeight.bold,
                                                  color: Colors.white)))),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Container(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          nardeban_data[index]['name'],
                                          style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.black54,
                                              fontWeight: FontWeight.w400),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            ),
                            Container(
                              width: (size.width - 120) * 0.32,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(10),
                                        border: Border.all(color: Colors.blue)),
                                    child: Padding(
                                      padding: const EdgeInsets.only(
                                          right: 10,
                                          bottom: 4,
                                          left: 10,
                                          top: 4),
                                      child: Row(
                                        children: [
                                          SizedBox(
                                            width: 25,
                                            height: 25,
                                            child: TextField(
                                              textAlign: TextAlign.center,
                                              keyboardType:
                                                  TextInputType.number,
                                              decoration: InputDecoration(
                                                hintText: '4%',
                                                border: InputBorder.none,
                                                contentPadding: EdgeInsets.only(
                                                  bottom: 8,
                                                  top: 3,
                                                ),
                                              ),
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                  // Icon(
                                  //   Icons.notifications,
                                  //   size: 22,
                                  //   color: Colors.blue.withOpacity(0.7),
                                  // )
                                ],
                              ),
                            )
                          ],
                        ),
                      )),
                ],
              );
            })),
          ],
        ),
      ),
    );
}

This is my json when I get it from the API call:

{
    "pellekan": [
        {
            "name": "1",
            "form": null,
            "to": "1000000",
            "percent": 1
        },
        {
            "name": "2",
            "form": "1000000",
            "to": 1100000,
            "percent": 2.89
        },
        {
            "name": "3",
            "form": "1000000",
            "to": 1200000,
            "percent": 4.79
        },
    ]
}

Also this is my class and I define stringResponse value out of that

var stringResponse = [];

class ResultLadder extends StatefulWidget implements PreferredSizeWidget {
  @override
  Size get preferredSize => const Size.fromHeight(100);

  const ResultLadder({Key? key}) : super(key: key);

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

Future<String> getToken() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('login')!;
}

class _ResultLadderState extends State<ResultLadder> {
  String token = "";
  @override
  void initState() {
    // getInfo();
    getDataLadder();
    super.initState();
  }

generally, for example how i can show name in json data instead of "14" , in this below:code:

child: Text("14",
     style: TextStyle(
     fontSize: 13.0,
     fontWeight: FontWeight.bold,
     color: Colors.white))

this is getDataLadder Code :

  Future getDataLadder() async {
    print('bye');
    String token = await getToken();
    var response = await http.get(
        Uri.parse('https://mylocalapiurl.com/backend/api/v1/pellekan/main/active'),
        headers: {
          'Content-type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        });
    print('Token : ${token}');
    print('Response Body : ${response.body}');
        
    if (response.statusCode == 200) {
      setState(() {
        stringResponse = json.decode(response.body);
      });
    }
    
  }

nardeban ladder is one file in data folder and i add this values for show data demo (this is working):

const List nardeban_data = [
  {
    "img":
        "https://images.unsplash.com/image.jpg",
    "name": "mark wiliams",
    "takhfif": "description item"
  },
  {
    "img":
        "https://images.unsplash.com/photo-1610859923380-c8e5a13165d1?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80",
    "name": "joe mark",
    "takhfif": "description item"
  },
];```
2
  • Can you show the code inside the getDataLadder() method? Also show a bit of how you are populating the property called ** nardeban_data**. Commented Feb 21, 2022 at 20:23
  • @RomanJaquez i added Commented Feb 21, 2022 at 21:43

1 Answer 1

2

So now use your stringResponse since it has already been decoded into JSON, I'd create a small PODO (Plain Ol' Dart Object) to map my JSON to the data you're receiving, as in:

class NardebanData {
   String? name;
   String? form;
   String? to;
   double? percent;
  
   NardebanData({ this.name, this.form, this.to, this.percent });
 
   factory NardebanData.fromJson(Map<String, dynamic> json) {
     return NardebanData(
        name: json['name'],
        form: json['form'], 
        to: json['to'],
        percent: json['percent']
     );
   }
}

Inside your setState() call, then map it as such:


setState(() {
 
 stringResponse = json.decode(response.body);

 nardeban_data = (stringResponse['pellekan'] as List<dynamic>).map((d) => NardebanData.fromJson(d)).toList();
});

So make your nardeban_data not a const anymore, but a List of NardebanData objects:

List<NardebanData> narbeban_data = [];

And when you consume it (inside of your List.generate) you could fetch the current object in the iteration, as in:

children: List.generate(nardeban_data.length, (index) {
   // fetch the item in the collection by the index provided
   NardebanData dataItem = nardeban_data[index];

   // ALL YOUR WIDGET STRUCTURE HERE
   // LIKE YOUR TEXT WIDGETS AS IN:
   Text(
     dataItem.name!, // pull the data out of the dataItem using the provided properties
     style: TextStyle(
       fontSize: 14,
       color: Colors.black54,
       fontWeight: FontWeight.w400),
       overflow: TextOverflow.ellipsis,
   ),
}

Also make sure your JSON data coming from your API is consistent as far as the type of data in each field, otherwise the decoding will fail (i.e. make sure that name, form, to are Strings, and percent is a double).

See if that works for you.

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

9 Comments

thank for your answer , but i have a error in setState , in this line nardeban_data = stringResponse['pellekan'].map((d) => NardebanData.fromJson(d))give me a error nardeban_data = stringResponse['pellekan'].map((d) => NardebanData.fromJson(d)) and Error: The method 'map' isn't defined for the class 'NardebanData'. also Try correcting the name to the name of an existing method, or defining a method named 'map'.
You could try to cast the stringResponse into a List<dynamic>., as in: (stringResponse[‘pellekan’] as List<dynamic>).map; this is based on the sample json output you put above that there is a property called pellekan that contains the array of objects
Sure, I'll update the code; here's also a DartPad Gist so you can see how it works in real time. Just hit "Run" and see the outcome on how I'm parsing your data. dartpad.dev/?c0eaeb623b66d2d7e33e9ec9920838c3
Yes that’s good - but check again the values that are coming from your API - you’re getting that error above because one of the properties is not the correct type - make sure they map correctly.
|

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.