Home > Software design >  how i can show all data from get api in flutter
how i can show all data from get api in flutter

Time:02-23

I have trouble displaying data, all data is received correctly from 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 style when i get from api:

{
    "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 difine 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=&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80",
    "name": "joe mark",
    "takhfif": "description item"
  },
];```

CodePudding user response:

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.

  • Related