androidjsonapiflutterjsonresponse

Flutter Snapshot.hasData is always returning true


i need to fetch data from server and sometimes the data can be empty response from logcat is data snapshot.data is returning instance of my model Instance of 'MyItems' and the response from server when data is not available is

{
    "data": []
}

the problem is snapshot.hasData is always returning true for empty response i have tested snapshot.data == null still its true.

Model class

import 'dart:convert';

MyItems myItemsFromJson(String str) => MyItems.fromJson(json.decode(str));

String myItemsToJson(MyItems data) => json.encode(data.toJson());

class MyItems {
  MyItems({
    this.dataa,
  });

  List<Datumm> dataa;

  factory MyItems.fromJson(Map<String, dynamic> json) => MyItems(
    dataa: List<Datumm>.from(json["data"].map((x) => Datumm.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "data": List<dynamic>.from(dataa.map((x) => x.toJson())),
  };
}

class Datumm {
  Datumm({
    this.userId,
    this.Name,
    this.MiddelName,
  
  });

  String userId;
  String Name;
  String MiddelName;
 

  factory Datumm.fromJson(Map<String, dynamic> json) => Datumm(
    userId: json["user_id"],
    Name: json["Name"],
    MiddelName: json["MiddleName"],
  
  );

  Map<String, dynamic> toJson() => {
    "user_id": userId,
    "Name": crbtCode,
    "MiddelName": artistName,
    
  };
}

My Future api call

 Future<MyItems> getUdata(String aName) async {
        var url =
            'https://cvbgng.com/test/${aName}';
    
        final response = await http.get(url).timeout(Duration(seconds: 15000));
    
        if (response.statusCode == 200) {
    
         
          return MyItems.fromJson(json.decode(response.body));
        } else {
          throw Exception('Faild to load');
        }
      }

Solution

  • check the condition as snapshot.data.dataa.isEmpty if it is true you have empty response.