Home > Back-end >  API's data is not showing on Listview using flutter
API's data is not showing on Listview using flutter

Time:08-31

I'm trying to get data from APIs, The data is being successfully fetched from the server but the issue is that when the data is provided to Listview it cant be shown. How can I show the data on Listview in a flutter/dart?

Following is the code for fetching data from API's

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';


Map mapResponse = {};
Map dataResponse = {};
List listResponse = {} as List;

class teamapilab extends StatefulWidget {
  @override
  State<teamapilab> createState() => _teamapilab();
}

// ignore: camel_case_types
class _teamapilab extends State<teamapilab> {
  Future team() async {
    http.Response response;
    response = await http
        .get(Uri.parse("https://www.archmage.lk/api/v1/webapi/get-teams"));
    if (response.statusCode == 200) {
      setState(() {
        //stringResponse = response.body;
        mapResponse = json.decode(response.body);
        listResponse = mapResponse['data'];
      });
    }
  }

  @override
  void initState() {
    team();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // ignore: avoid_unnecessary_containers
    return ListView.builder(
      itemBuilder: (context, index) {
        return Container(
          child: Column(children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: CircleAvatar(
                backgroundImage:
                    NetworkImage(listResponse[index]['member_image']),
              ),
            ),
            Text(listResponse[index]['name'].toString()),
            Text(listResponse[index]['status'].toString()),
          ]),
        );
      },
      // ignore: unnecessary_null_comparison
      itemCount: listResponse == null ? 0 : listResponse.length,
    );
  }
}

CodePudding user response:

It is Not good to use async in initState instead using FutureBuilder. Try this:

class Teamapilab extends StatefulWidget {
  @override
  State<Teamapilab> createState() => _Teamapilab();
}

class _Teamapilab extends State<Teamapilab> {
  Future<List> team() async {
    http.Response response;
    response = await http
        .get(Uri.parse("https://www.archmage.lk/api/v1/webapi/get-teams"));
    if (response.statusCode == 200) {
      Map mapResponse = json.decode(response.body);
      return mapResponse['data'] as List;
    } else {
      return [];
    }
  }

  @override
  void initState() {
    // team();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FutureBuilder<List?>(
            future: team(),
            builder: (context, snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.waiting:
                  return Text('Loading....');
                default:
                  if (snapshot.hasError) {
                    return Text('Error: ${snapshot.error}');
                  } else {
                    List data = snapshot.data ?? [];

                    return ListView.builder(
                      itemBuilder: (context, index) {
                        return Column(children: [
                          Container(
                            padding: const EdgeInsets.all(8.0),
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                            ),
                            height: 50,
                            width: 50,
                            child: Image(
                                errorBuilder: (context, object, trace) {
                                  return Container(
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: Colors.red,
                                    ),
                                  );
                                },
                                image: NetworkImage(
                                  data[index]['member_image'] ?? '',
                                )),
                          ),
                          Text('${data[index]['name']}'),
                          Text('${data[index]['status']}'),
                        ]);
                      },
                      itemCount: data.length,
                    );
                  }
              }
            }),
      ),
    );
  }
}

enter image description here

CodePudding user response:

List listResponse = {} as List; should be replaced with List listResponse = [] as List;

In dart {} is empty map and [] is empty list.

CodePudding user response:

You can use below code.

import 'dart:convert';

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

Map mapResponse = {};
Map dataResponse = {};
List listResponse = {} as List;

class teamapilab extends StatefulWidget {
  @override
  State<teamapilab> createState() => _teamapilab();
}

// ignore: camel_case_types
class _teamapilab extends State<teamapilab> {

  bool dataLoaded = false;

  Future team() async {
    http.Response response;
    response = await http
        .get(Uri.parse("https://www.archmage.lk/api/v1/webapi/get-teams"));
    if (response.statusCode == 200) {
      setState(() {
        //stringResponse = response.body;
        mapResponse = json.decode(response.body);
        print("DAata "   mapResponse.toString());
        listResponse = mapResponse['data'];
        print("DAata "   listResponse.toString());
        dataLoaded = true;
        setState(() {});
      });
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) async{
      await team();
    });
  }

  @override
  Widget build(BuildContext context) {
    // ignore: avoid_unnecessary_containers
    return Scaffold(
      body: dataLoaded
          ? ListView.builder(
        scrollDirection: Axis.vertical,
        itemBuilder: (context, index) {
          return Column(children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: CircleAvatar(
                backgroundImage:
                NetworkImage(listResponse[index]['member_image']),
              ),
            ),
            Text(listResponse[index]['name'].toString()),
            Text(listResponse[index]['status'].toString()),
          ]);
        },
        // ignore: unnecessary_null_comparison
        itemCount: listResponse == null ? 0 : listResponse.length,
      )
          : const CircularProgressIndicator(),
    );
  }
}
  • Related