How can I display Image if my list is empty?

3,894

Solution 1

Try this,

import 'dart:convert';

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

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() => runApp(MaterialApp(home: MyWidget()));

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  Future<List<NewAddressModel>> newAddress;

  @override
  void initState() {
    newAddress = hitGetAddressApi();
    super.initState();
  }

  Future<List<NewAddressModel>> hitGetAddressApi() async {
    final response = await http.post("api");
    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      if (responseBody is List)
        return responseBody
            .map((data) => new NewAddressModel.fromJson(data))
            .toList();
      else {
        print(responseBody);
        return null;
      }
    } else {
      print(response.statusCode);
      throw Exception("Problem in fetching address List");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<NewAddressModel>>(
        future: newAddress,
        builder: (context, snapShot) {
          if (snapShot.connectionState == ConnectionState.waiting)
            return Center(
              child: CircularProgressIndicator(),
            );
          else if (snapShot.hasError) {
            return Center(
              child: Text("ERROR: ${snapShot.error}"),
            );
          } else {
            if (snapShot.hasData && snapShot.data.isNotEmpty)
              return getListView(snapShot.data);
            else //`snapShot.hasData` can be false if the `snapshot.data` is null
              return Center(
                child: Text("No Data Found"),
              );
          }
        },
      ),
    );
  }

  Widget getListView(List<NewAddressModel> addressList) {
    return ListView.builder(
      itemCount: addressList.length,
      itemBuilder: (BuildContext context, int index) {
        final address = addressList[index];
        //Change `addressViewCard` to accept an `NewAddressModel` object
        return addressViewCard(address);
      },
    );
  }

  Widget addressViewCard(NewAddressModel address) {
    //implement based on address instead of index
    return ListTile(title: Text("${address.address}"));
  }
}

class NewAddressModel {
  String id;
  String name;
  String mobile;
  String address;
  String state;
  String city;
  String pin;
  String userid;

  NewAddressModel({
    this.id,
    this.name,
    this.mobile,
    this.address,
    this.state,
    this.city,
    this.pin,
    this.userid,
  });

  factory NewAddressModel.fromJson(Map<String, dynamic> json) =>
      NewAddressModel(
        id: json["id"],
        name: json["name"],
        mobile: json["mobile"],
        address: json["address"],
        state: json["state"],
        city: json["city"],
        pin: json["pin"],
        userid: json["userid"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "mobile": mobile,
        "address": address,
        "state": state,
        "city": city,
        "pin": pin,
        "userid": userid,
      };
}

Solution 2

FutureBuilder<AsyncSnapshot<AsyncSnapshot>>(
        builder: (context, snap) {
          if (snap.connectionState != ConnectionState.done) {
            return Text("loading");
          } else {
            if (snap.hasError) {
              return Text([snap.error.toString()]); 
            }
            else {
              if (snap.hasData) {


                return getListView("${snap.data}");
              } else {
                return Text("No DAta");
              }
            }
          }
        },
        future:
        methodToGetAPIResult(),
    );

Solution 3

I would like to tell you that please use FutureBuilder for this kind of usage. In your code i am not sure where you are changing state of isLoading flag.

So please update your question, and please be sure that you are changing isLoading flag in proper scope.

Please refer this for implementation of FutureBuilder

Solution 4

A better way is to use FutureBuilder here you have all sorts of checks

Share:
3,894
Jorden
Author by

Jorden

Updated on December 17, 2022

Comments

  • Jorden
    Jorden over 1 year

    I want to display an Image or Text in Center like No Record Found all details are fetched from API. In Native Android setEmptyView() for this condition but no idea how can I do this in flutter. Non-stop progress Dialog is running but the text is not displayed. I added code with my JSON response

    List<NewAddressModel> newAddress = List();
    bool isLoading = false;
    
    Scaffold(
    body :isLoading
              ? Center(
            child: CircularProgressIndicator(),
          )
              : Container(
              color: Color.fromRGBO(234, 236, 238, 1),
              child: getListView()
          ),
    )
    
    Widget getListView(){
        return newAddress.isNotEmpty ?
        ListView.builder(itemCount: newAddress.length,
            itemBuilder: (BuildContext context, int index) {
              return addressViewCard(index);
            }
    
        )
            : Center(child: Text("No Found"));
      }
    
    Future<List>hitGetAddressApi() async {
        setState(() {
          isLoading = true;
        });
        final response = await http.post(api);
    
        var userDetails = json.decode(response.body);
        if (response.statusCode == 200) {
          newAddress = (json.decode(response.body) as List)
              .map((data) => new NewAddressModel.fromJson(data))
              .toList();
          setState(() {
            isLoading = false;
            newAddressModel = new NewAddressModel.fromJson(userDetails[0]);
          });
        }
    
    
        return userDetails;
      }
    
    This is JSON Response which I am getting from my API.
    [
        {
            "id": "35",
            "name": "Toyed",
            "mobile": "8855226611",
            "address": "House No 100",
            "state": "Delhi",
            "city": "New Delhi",
            "pin": "000000",
            "userid": "2",
        }
    ]
    
    
  • Jorden
    Jorden about 4 years
    Every time execute error block if no data in the list.
  • Dev
    Dev about 4 years
    Please explain what happens
  • Jorden
    Jorden about 4 years
    Every time this if (snap.hasError) { return Text([snap.error.toString()]); } block executed.
  • Jorden
    Jorden about 4 years
    If my list is null
  • Jorden
    Jorden about 4 years
    Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast
  • Jorden
    Jorden about 4 years
    This exception is occurs
  • Crazy Lazy Cat
    Crazy Lazy Cat about 4 years
    @Toyed Is the response body a list? Can you add example json response in your question?
  • Jorden
    Jorden about 4 years
    Yes, I am adding
  • Crazy Lazy Cat
    Crazy Lazy Cat about 4 years
    @Toyed I added code with NewAddressModel class. if you get the same error then add that log too. thank you
  • Jorden
    Jorden about 4 years
    This time getting this error . ERROR : NoSuchMethodError : The method ' map ' was called on null . Receiver : null Tried calling : map < NewAddressModel > ( Closure : ( dynamic ) = > NewAddressModel )
  • Dev
    Dev about 4 years
    what is output of [snap.error.toString()] in this case as it seems there is an error in getting snap
  • Crazy Lazy Cat
    Crazy Lazy Cat about 4 years
    @Toyed I think your server sending null response. in the previous error it may have sent a` map try printing response.body
  • Jorden
    Jorden about 4 years
    API returns {"message":"No Data Found"} when I hit it in Postman but when I try to print response.body nothing is displaying the same pervious error occurs
  • Crazy Lazy Cat
    Crazy Lazy Cat about 4 years
    I am not sure why the server returning 200 response for "No data found".
  • Crazy Lazy Cat
    Crazy Lazy Cat about 4 years
    @Toyed I updated the code. Understand how to handle response body data and json convert. then you can manipulate them easily.
  • Jorden
    Jorden about 4 years
  • Jorden
    Jorden about 4 years
    hey can you help me in this query stackoverflow.com/questions/60433200/…