Home > Software design >  Flutter ListView remove empty values from json object in flutter
Flutter ListView remove empty values from json object in flutter

Time:11-14

I am working on my test project and i check all null value but it didnt worked from my side. Always showing empty list view. Is there any way to solve this issue it will be very helpful! Here is my screenshot to remove blank list item: enter image description here

API Endpoint: check api here

Model Class:

`

import 'dart:convert';

List<EmployeeResponseModel> employeeResponseModelFromJson(String str) =>
    List<EmployeeResponseModel>.from(
        json.decode(str).map((x) => EmployeeResponseModel.fromJson(x)));

String employeeResponseModelToJson(List<EmployeeResponseModel> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class EmployeeResponseModel {
  EmployeeResponseModel({
    this.id,
    this.name,
    this.company,
    this.designation,
    this.companyLogo,
  });

  final int? id;
  final String? name;
  final String? company;
  final String? designation;
  final String? companyLogo;

  factory EmployeeResponseModel.fromJson(Map<String, dynamic> json) =>
      EmployeeResponseModel(
        id: json["id"] == "null" ? '' : json["id"],
        name: json["name"] == "null" ? '' : json["name"],
        company: json["company"] == "null" ? '' : json["company"],
        designation: json["designation"] == "null" ? '' : json["designation"],
        companyLogo: json["company_logo"] == "null" ? '' : json["company_logo"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "company": company,
        "designation": designation,
        "company_logo": companyLogo,
      };
}

`

Provider:

`

class EmployeeProvider extends ChangeNotifier {
  bool isAuthenticated = false;

  Future<List<EmployeeResponseModel>?> getAllEmployee() async {
    try {
      http.Response response = await http.get(
        Uri.parse(ApiBaseUrl().employeeBaseUrl),
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
        },
      );

      if (response.statusCode == 200) {
        final parsed = json.decode(response.body);

        notifyListeners();
        return parsed
            .map<EmployeeResponseModel>(
                (json) => EmployeeResponseModel.fromJson(json))
            .toList();
      } else {
        throw Exception(AppStrings.failedToLoadEmployeeList);
      }
    } on SocketException {
      throw AppStrings.noInternet;
    }
  }
}

`

Render list to UI:

`

class EmployeeList extends StatefulWidget {
  const EmployeeList({super.key});

  @override
  State<EmployeeList> createState() => _EmployeeListState();
}

class _EmployeeListState extends State<EmployeeList> {
  late Future<List<EmployeeResponseModel>?> _employeeModelList;

  void initState() {
    getAllEmployee();
    super.initState();
  }

  Future<void> getAllEmployee() async {
    setState(() {
      _employeeModelList = Provider.of<EmployeeProvider>(context, listen: false)
          .getAllEmployee();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(AppStrings.employeeList),
        backgroundColor: Colors.blue,
      ),
      body: RefreshIndicator(
        onRefresh: getAllEmployee,
        child: SingleChildScrollView(
          physics: const ScrollPhysics(),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              FutureBuilder<List<EmployeeResponseModel>?>(
                future: _employeeModelList,
                builder: (context, snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.none:
                    case ConnectionState.active:
                    case ConnectionState.waiting:
                      return ListView.builder(
                          itemCount: 10,
                          shrinkWrap: true,
                          itemBuilder: (context, index) {
                            return skeltonBuild();
                          });
                    case ConnectionState.done:
                      if (snapshot.hasData && snapshot.data!.isNotEmpty) {
                        return Flexible(
                          child: ListView.builder(
                            itemCount: snapshot.data!.length,
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            itemBuilder: (_, index) {
                              return EmployeeListWidget(
                                name: snapshot.data![index].name.toString(),
                                company:
                                    snapshot.data![index].company.toString(),
                                designation: snapshot.data![index].designation
                                    .toString(),
                                company_logo: snapshot.data![index].companyLogo
                                    .toString(),
                                onTap: () => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          const EmployeeDetails()),
                                ),
                              );
                            },
                          ),
                        );
                      } else {
                        return Padding(
                          padding: EdgeInsets.only(
                              top: MediaQuery.of(context).size.height * 0.2),
                          child: NoInternetConnection(
                              message: snapshot.error.toString()),
                        );
                      }
                  }
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

`

Widget:

`

class EmployeeListWidget extends StatelessWidget {
  final String name;
  final String company;
  final String designation;
  final String company_logo;
  final VoidCallback? onTap;
  const EmployeeListWidget(
      {super.key,
      required this.name,
      required this.company,
      required this.designation,
      required this.company_logo,
      required this.onTap});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(4.0, 0.0, 4.0, 0.0),
        child: Card(
          elevation: 2.0,
          child: Padding(
            padding: const EdgeInsets.all(4.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (name != "null")
                      Text(name.toString(),
                          style: const TextStyle(
                              fontSize: 16,
                              color: Colors.black87,
                              fontWeight: FontWeight.bold)),
                    const SizedBox(height: 4),
                    if (company != "null")
                      SmallGreyTextIcon(
                          text: company, icon: Icons.apartment_outlined),
                    const SizedBox(height: 4),
                    if (designation != "null")
                      SmallGreyTextIcon(
                          text: designation, icon: Icons.badge_outlined),
                  ],
                ),
                const SizedBox(
                  height: 4,
                ),
                if (company_logo != "null")
                  CachedNetworkImage(
                    imageUrl: company_logo,
                    width: 50,
                    height: 50,
                    placeholder: (context, url) =>
                        const CircularProgressIndicator(),
                    errorWidget: (context, url, error) =>
                        const Icon(Icons.error),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

`

Please help me to find this better way to handle this problem.

I have tried null check and validatin it still show blank list. I wan tot remove that blank list value from list view.

CodePudding user response:

Your itemCount should be based on your data length. in your case, it should be itemCount: snapshot.docs.length

CodePudding user response:

You should remove all the objects with no name property.

Something like this should work:

if (response.statusCode == 200) {
    final parsed = json.decode(response.body);
    parsed = parsed.where((element) => element['name'] != null); // <- Add this line
    notifyListeners();
    return parsed
        .map<EmployeeResponseModel>(
            (json) => EmployeeResponseModel.fromJson(json))
        .toList();
  } else {
    throw Exception(AppStrings.failedToLoadEmployeeList);
  }
} on SocketException {
  throw AppStrings.noInternet;
}
  • Related