Home > database >  Null check operator used on a null value error while using ! operator in flutter
Null check operator used on a null value error while using ! operator in flutter

Time:09-30

In my project i accessed my model with api request. but when i run it it throws "Null check operator used on a null value" i've used the same method before and it works fine. i don't know what happened on this one.

my model

class Client {
  List<Clients>? clients;

  Client({this.clients});

  Client.fromJson(Map<String, dynamic> json) {
    if (json['clients'] != null) {
      clients = <Clients>[];
      json['clients'].forEach((v) {
        clients!.add(new Clients.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.clients != null) {
      data['clients'] = this.clients!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Clients {
  int? id;
  String? name;
  String? address;
  String? tinNo;
  String? status;
  String? createdAt;
  String? updatedAt;
  List<Phones>? phones;

  Clients(
      {this.id,
      this.name,
      this.address,
      this.tinNo,
      this.status,
      this.createdAt,
      this.updatedAt,
      this.phones});

  Clients.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    address = json['address'];
    tinNo = json['tin_no'];
    status = json['status'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
    if (json['phones'] != null) {
      phones = <Phones>[];
      json['phones'].forEach((v) {
        phones!.add(new Phones.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['address'] = this.address;
    data['tin_no'] = this.tinNo;
    data['status'] = this.status;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    if (this.phones != null) {
      data['phones'] = this.phones!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Phones {
  int? id;
  String? clientId;
  Null? supplierId;
  Null? companyId;
  String? phoneNumber;
  String? email;
  String? model;
  String? category;
  String? createdAt;
  String? updatedAt;

  Phones(
      {this.id,
      this.clientId,
      this.supplierId,
      this.companyId,
      this.phoneNumber,
      this.email,
      this.model,
      this.category,
      this.createdAt,
      this.updatedAt});

  Phones.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    clientId = json['client_id'];
    supplierId = json['supplier_id'];
    companyId = json['company_id'];
    phoneNumber = json['phone_number'];
    email = json['email'];
    model = json['model'];
    category = json['category'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['client_id'] = this.clientId;
    data['supplier_id'] = this.supplierId;
    data['company_id'] = this.companyId;
    data['phone_number'] = this.phoneNumber;
    data['email'] = this.email;
    data['model'] = this.model;
    data['category'] = this.category;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    return data;
  }
}

for my project i'm using paginated data table and accessing this data. the code is as follows. i've used the data as datasList[0].clients![index].address.toString(), in my datatablesource. and passed that data as

DataTableSource dataSource(List<Client> userList) =>
      MyTable(datasList: userList, context: context);

data source

source: dataSource(
                                  clientController.foundClients.value)

the error is when i use the ! operator. so how can i use this properly?

where the code being used

Container(
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(15),
                    border: Border.all(color: Colors.grey)),
                child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: width * 0.01),
                    child: Obx(() {
                      return clientController.clientPress
                          ? const Center(child: CircularProgressIndicator())
                          : PaginatedDataTable(
                              sortColumnIndex: sortColumnIndex,
                              sortAscending: isAscending,
                              columns: [
                                DataColumn(
                                    label: const Text("Id"),
                                    onSort: (sortColumnIndex, ascending) {
                                      setState(() {
                                        isAscending = !isAscending;
                                      });
                                      // onSort(sortColumnIndex, ascending);
                                    }),
                                DataColumn(
                                    label: const Text("Name"),
                                    onSort: (sortColumnIndex, ascending) {
                                      setState(() {
                                        isAscending = !isAscending;
                                      });
                                      //onSort(sortColumnIndex, ascending);
                                    }),
                                DataColumn(
                                    label: const Text("Address"),
                                    onSort: (sortColumnIndex, ascending) {
                                      setState(() {
                                        isAscending = !isAscending;
                                      });
                                      //onSort(sortColumnIndex, ascending);
                                    }),
                                DataColumn(
                                    label: const Text("Tin No"),
                                    onSort: (sortColumnIndex, ascending) {
                                      setState(() {
                                        isAscending = !isAscending;
                                      });
                                      // onSort(sortColumnIndex, ascending);
                                    }),
                                const DataColumn(label: Text("Status")),
                                const DataColumn(label: Text("Created At")),
                                const DataColumn(label: Text("Actions")),
                              ],
                              header: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  !isSearch
                                      ? Expanded(
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text(
                                                "Manage Users",
                                                style: TextStyle(
                                                    fontSize: width * 0.04,
                                                    fontWeight:
                                                        FontWeight.normal),
                                              ),
                                              IconButton(
                                                  onPressed: () {
                                                    setState(() {
                                                      isSearch = !isSearch;
                                                    });
                                                  },
                                                  icon: Icon(Icons.search))
                                            ],
                                          ),
                                        )
                                      : ConstrainedBox(
                                          constraints: BoxConstraints(
                                              maxWidth: width * 0.5),
                                          child: SizedBox(
                                            width: width * 0.6,
                                            child: TextField(
                                              decoration: InputDecoration(
                                                  suffixIcon: IconButton(
                                                      onPressed: () {
                                                        setState(() {
                                                          searchController
                                                              .clear;
                                                          // userController
                                                          //     .filterUser('');
                                                          isSearch = !isSearch;
                                                        });
                                                      },
                                                      icon: const Icon(
                                                          Icons.close)),
                                                  hintText: "search"),
                                              onChanged: (text) {
                                                text = text.toLowerCase();
                                                // userController.filterUser(text);
                                              },
                                            ),
                                          ),
                                        ),
                                  MaterialButton(
                                    onPressed: () {
                                      showMaterialModalBottomSheet(
                                          context: context,
                                          builder: (context) => SizedBox(
                                                height: height * 0.9,
                                                // child: BottomSheetWidget(),
                                              ),
                                          shape: const RoundedRectangleBorder(
                                              borderRadius: BorderRadius.only(
                                                  topLeft: Radius.circular(15),
                                                  topRight:
                                                      Radius.circular(15))));
                                    },
                                    color: const Color.fromRGBO(30, 119, 66, 1),
                                    shape: RoundedRectangleBorder(
                                        borderRadius:
                                            BorderRadius.circular(10)),
                                    child: Text(
                                      "Add User",
                                      style: TextStyle(
                                          color: Colors.white,
                                          fontSize: width * 0.03),
                                    ),
                                  )
                                ],
                              ),
                              source: dataSource(
                                  clientController.foundClients.value));
                    })),
              )

this is how I'm passing the fetch to my list using Getx

import 'package:get/get.dart';
import 'package:store_mgt_project/models/client/client_api.dart';
import 'package:store_mgt_project/models/client/client_model.dart';

class ClientController extends GetxController {
  final _clientPress = false.obs;
  get clientPress => _clientPress.value;
  set clientPress(value) => _clientPress.value = value;

  var allCLients = <Client>[].obs;
  var foundClients = <Client>[].obs;

  @override
  void onInit() {
    super.onInit();
    fetchClient().then(
        (value) => {allCLients.value = value, foundClients.value = allCLients});
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {}
  void filterClient(String user, int index) {
    List<Client> results = [];
    if (user.isEmpty) {
      results = allCLients;
    } else {
      results = allCLients.where((element) {
        var _name = element.clients![index].name!.toLowerCase();
        var _username = element.clients![index].address!.toLowerCase();
        return _name.contains(user.toLowerCase()) ||
            _username.contains(user.toLowerCase());
      }).toList();
    }
    foundClients.value = results;
  }

  setclientPress(bool value) {
    clientPress = value;
    update();
  }
}

so in the code I'm using controller and getting the datas

CodePudding user response:

Try the following code:

class Client {
  List<Clients>? clients;

  Client({this.clients});

  Client.fromJson(Map<String, dynamic> json) {
    if (json['clients'] != null) {
      clients = <Clients>[];
      json['clients'].forEach((v) {
        clients?.add(new Clients.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.clients != null) {
      data['clients'] = this.clients?.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Clients {
  int? id;
  String? name;
  String? address;
  String? tinNo;
  String? status;
  String? createdAt;
  String? updatedAt;
  List<Phones>? phones;

  Clients(
      {this.id,
      this.name,
      this.address,
      this.tinNo,
      this.status,
      this.createdAt,
      this.updatedAt,
      this.phones});

  Clients.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    address = json['address'];
    tinNo = json['tin_no'];
    status = json['status'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
    if (json['phones'] != null) {
      phones = <Phones>[];
      json['phones'].forEach((v) {
        phones?.add(new Phones.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['address'] = this.address;
    data['tin_no'] = this.tinNo;
    data['status'] = this.status;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    if (this.phones != null) {
      data['phones'] = this.phones?.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Phones {
  int? id;
  String? clientId;
  Null? supplierId;
  Null? companyId;
  String? phoneNumber;
  String? email;
  String? model;
  String? category;
  String? createdAt;
  String? updatedAt;

  Phones(
      {this.id,
      this.clientId,
      this.supplierId,
      this.companyId,
      this.phoneNumber,
      this.email,
      this.model,
      this.category,
      this.createdAt,
      this.updatedAt});

  Phones.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    clientId = json['client_id'];
    supplierId = json['supplier_id'];
    companyId = json['company_id'];
    phoneNumber = json['phone_number'];
    email = json['email'];
    model = json['model'];
    category = json['category'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['client_id'] = this.clientId;
    data['supplier_id'] = this.supplierId;
    data['company_id'] = this.companyId;
    data['phone_number'] = this.phoneNumber;
    data['email'] = this.email;
    data['model'] = this.model;
    data['category'] = this.category;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    return data;
  }
}

CodePudding user response:

Change your Client model to this, to make sure always have value:

class Client {
  List<Clients> clients;

  Client({required this.clients});
  static Client fromJson(Map<String, dynamic> json) {
    if (json['clients'] != null) {
      var _clients = <Clients>[];
      json['clients'].forEach((v) {
        _clients.add(new Clients.fromJson(v));
      });
      return Client(clients: _clients);
    } else {
      return Client(clients: []);
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.clients != null) {
      data['clients'] = this.clients!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}
  • Related