0

I have Business Model. I used that model for posting data in post api. but when i store data in this Business? business = Business(); business.bank!.bankName = _selectedIdProof.toString(); then i got errror.

I have Business Model. I used that model for posting data in post api. but when i store data in this Business? business = Business(); business.bank!.bankName = _selectedIdProof.toString(); then i got errror. I have Business Model. I used that model for posting data in post api. but when i store data in this Business? business = Business(); business.bank!.bankName = _selectedIdProof.toString(); then i got errror.

please help me I am not getting to how to di this.

import 'dart:convert';

import 'package:evillage_app/models/business/business.dart';
import 'package:evillage_app/models/business/proof/proof.dart';
import 'package:evillage_app/screens/businessPages/bank_details.dart';
import 'package:evillage_app/screens/businessPages/business_registration.dart';
import 'package:evillage_app/screens/businessPages/customStepperPage.dart';
import 'package:evillage_app/style/style.dart';
import 'package:evillage_app/widget/button2.dart';
import 'package:evillage_app/widget/my_appbar_noSearch.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:multi_image_picker2/multi_image_picker2.dart';

class ShopCertificationPage extends StatefulWidget {
  const ShopCertificationPage({Key? key}) : super(key: key);

  @override
  _ShopCertificationPageState createState() => _ShopCertificationPageState();
}

class _ShopCertificationPageState extends State<ShopCertificationPage> {
  String? _selectedIdProof;
  String? _selectedAddProof;

  TextEditingController _panNumController = TextEditingController();
  TextEditingController _gstNumController = TextEditingController();

  //multi image picker
  List<Asset> idProofImagesList = <Asset>[];
  List<Asset> idProofResultList = <Asset>[];

  List<Asset> addProofImagesList = <Asset>[];
  List<Asset> addProofResultList = <Asset>[];

  List<Asset> panProofImagesList = <Asset>[];
  List<Asset> panProofResultList = <Asset>[];

  List<Asset> gstProofImagesList = <Asset>[];
  List<Asset> gstProofResultList = <Asset>[];

  List<Asset> shopCertificateImagesList = <Asset>[];
  List<Asset> shopCertificateResultList = <Asset>[];

  Future<void> idProofLoadAssets() async {
    if (idProofResultList == null) {
      idProofResultList = <Asset>[];
    }
    print("resultList" + idProofResultList.toString());
    String error = 'No Error Detected';
    try {
      idProofResultList = await MultiImagePicker.pickImages(
        maxImages: 10,
        enableCamera: true,
        selectedAssets: idProofImagesList,
        cupertinoOptions: CupertinoOptions(
          takePhotoIcon: "chat",
          doneButtonTitle: "Fatto",
        ),
        materialOptions: MaterialOptions(
          actionBarColor: "#4B7F3B",
          actionBarTitle: "E-Village",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }
    if (!mounted) return;
    setState(() {
      idProofImagesList = idProofResultList;
      // _error = error;
      print('images' + idProofImagesList.toString());
    });
  }

  Future<void> addProofLoadAssets() async {
    if (addProofResultList == null) {
      addProofResultList = <Asset>[];
    }
    print("resultList" + addProofResultList.toString());
    String error = 'No Error Detected';
    try {
      addProofResultList = await MultiImagePicker.pickImages(
        maxImages: 10,
        enableCamera: true,
        selectedAssets: addProofImagesList,
        cupertinoOptions: CupertinoOptions(
          takePhotoIcon: "chat",
          doneButtonTitle: "Fatto",
        ),
        materialOptions: MaterialOptions(
          actionBarColor: "#4B7F3B",
          actionBarTitle: "E-Village",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }
    if (!mounted) return;
    setState(() {
      addProofImagesList = addProofResultList;
      // _error = error;
      print('images' + addProofImagesList.toString());
    });
  }

  Future<void> panProofLoadAssets() async {
    if (panProofResultList == null) {
      panProofResultList = <Asset>[];
    }
    print("resultList" + panProofResultList.toString());
    String error = 'No Error Detected';
    try {
      panProofResultList = await MultiImagePicker.pickImages(
        maxImages: 10,
        enableCamera: true,
        selectedAssets: panProofImagesList,
        cupertinoOptions: CupertinoOptions(
          takePhotoIcon: "chat",
          doneButtonTitle: "Fatto",
        ),
        materialOptions: MaterialOptions(
          actionBarColor: "#4B7F3B",
          actionBarTitle: "E-Village",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }
    if (!mounted) return;
    setState(() {
      panProofImagesList = panProofResultList;
      // _error = error;
      print('images' + panProofImagesList.toString());
    });
  }

  Future<void> gstProofLoadAssets() async {
    if (gstProofResultList == null) {
      gstProofResultList = <Asset>[];
    }
    print("resultList" + gstProofResultList.toString());
    String error = 'No Error Detected';
    try {
      gstProofResultList = await MultiImagePicker.pickImages(
        maxImages: 10,
        enableCamera: true,
        selectedAssets: gstProofImagesList,
        cupertinoOptions: CupertinoOptions(
          takePhotoIcon: "chat",
          doneButtonTitle: "Fatto",
        ),
        materialOptions: MaterialOptions(
          actionBarColor: "#4B7F3B",
          actionBarTitle: "E-Village",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }
    if (!mounted) return;
    setState(() {
      gstProofImagesList = gstProofResultList;
      // _error = error;
      print('images' + gstProofImagesList.toString());
    });
  }

  Future<void> shopCertificateLoadAssets() async {
    if (shopCertificateResultList == null) {
      shopCertificateResultList = <Asset>[];
    }
    print("resultList" + shopCertificateResultList.toString());
    String error = 'No Error Detected';
    try {
      shopCertificateResultList = await MultiImagePicker.pickImages(
        maxImages: 10,
        enableCamera: true,
        selectedAssets: shopCertificateImagesList,
        cupertinoOptions: CupertinoOptions(
          takePhotoIcon: "chat",
          doneButtonTitle: "Fatto",
        ),
        materialOptions: MaterialOptions(
          actionBarColor: "#4B7F3B",
          actionBarTitle: "E-Village",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }
    if (!mounted) return;
    setState(() {
      shopCertificateImagesList = shopCertificateResultList;
      // _error = error;
      print('images' + shopCertificateImagesList.toString());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: ListView(
          shrinkWrap: true,
          physics: ScrollPhysics(),
          children: [
            SizedBox(height: 30),
            Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text(
                      "ID PROOF",
                      style: labelStyle().copyWith(fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                SizedBox(
                  height: 5,
                ),
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        height: 35,
                        padding: EdgeInsets.only(top: 0, left: 4, bottom: 0),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(color: greyc, width: 0.5)),
                        child: DropdownButtonHideUnderline(
                          child: DropdownButton<String>(
                            focusColor: Colors.red,
                            hint: Text(
                              "--Select Document--".tr(),
                              style: TextStyle(
                                  fontSize: 13, fontWeight: FontWeight.w500),
                              overflow: TextOverflow.ellipsis,
                            ),
                            value: _selectedIdProof,
                            isExpanded: true,
                            elevation: 2,
                            icon: Icon(
                              // Add this
                              Icons.arrow_drop_down, // Add this
                              color: mPrimaryColorLight, // Add this
                            ),
                            items: <String>[
                              'Passport'.tr(),
                              'Driving License'.tr(),
                              'Voter Id'.tr(),
                            ].map((String value) {
                              return DropdownMenuItem<String>(
                                value: value,
                                child: new Text(
                                  value,
                                  style: TextStyle(
                                      fontSize: 13,
                                      fontWeight: FontWeight.w500),
                                  overflow: TextOverflow.ellipsis,
                                ),
                              );
                            }).toList(),
                            onChanged: (String? val) {
                              setState(() {
                                _selectedIdProof = val;
                              });
                            },
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 7,
                    ),
                    InkWell(
                      onTap: () {
                        idProofLoadAssets();
                      },
                      child: Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: 18, vertical: 5),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                            gradient: whiteGrayGradient),
                        child: Row(
                          children: [
                            Icon(
                              Icons.cloud_upload_outlined,
                              color: Colors.black54,
                            ),
                            SizedBox(
                              width: 5,
                            ),
                            Text(
                              "Upload",
                              style: cardBlackText().copyWith(
                                  fontSize: 15, color: Colors.black54),
                            )
                          ],
                        ),
                      ),
                    )
                  ],
                ),
                SizedBox(
                  height: 10,
                ),
                idProofImagesList.length != 0
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            width: MediaQuery.of(context).size.width / 1.5,
                            height: MediaQuery.of(context).size.height / 6,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8),
                                border: Border.all(color: greyc, width: 0)),
                            child: GridView.count(
                              crossAxisCount: 3,
                              children: List.generate(idProofImagesList.length,
                                  (index) {
                                Asset asset = idProofImagesList[index];
                                return Container(
                                  padding: EdgeInsets.all(6),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(8)),
                                  child: AssetThumb(
                                    asset: asset,
                                    width: 600,
                                    height: 600,
                                  ),
                                );
                              }),
                            ),
                          )
                        ],
                      )
                    : Container()
              ],
            ),
           
              ],
            ),
            SizedBox(
              height: 30,
            ),
            Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text(
                      "PAN NO",
                      style: labelStyle().copyWith(fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                SizedBox(
                  height: 5,
                ),
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        height: 32,
                        // width: MediaQuery.of(context).size.width / 2.29,
                        child: TextFormField(
                          controller: _panNumController,
                          maxLength: 10,
                          keyboardType: TextInputType.text,
                          decoration: InputDecoration(
                              hintText: 'Enter 10 Digit PAN No',
                              counterText: "",
                              contentPadding: EdgeInsets.symmetric(
                                  horizontal: 10, vertical: 0),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(color: greyc, width: 0),
                              ),
                              focusedBorder: OutlineInputBorder(
                                  borderSide: BorderSide(
                                      color: mPrimaryColor, width: 1.0),
                                  borderRadius: BorderRadius.circular(8.0))),
                          onChanged: (value) {},
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 7,
                    ),
                    InkWell(
                      onTap: () {
                        panProofLoadAssets();
                      },
                      child: Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: 18, vertical: 5),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                            gradient: whiteGrayGradient),
                        child: Row(
                          children: [
                            Icon(
                              Icons.cloud_upload_outlined,
                              color: Colors.black54,
                            ),
                            SizedBox(
                              width: 5,
                            ),
                            Text(
                              "Upload",
                              style: cardBlackText().copyWith(
                                  fontSize: 15, color: Colors.black54),
                            )
                          ],
                        ),
                      ),
                    )
                  ],
                ),
                SizedBox(
                  height: 10,
                ),
                panProofImagesList.length != 0
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            width: MediaQuery.of(context).size.width / 1.5,
                            height: MediaQuery.of(context).size.height / 6,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8),
                                border: Border.all(color: greyc, width: 0)),
                            child: GridView.count(
                              crossAxisCount: 3,
                              children: List.generate(panProofImagesList.length,
                                  (index) {
                                Asset asset = panProofImagesList[index];
                                return Container(
                                  padding: EdgeInsets.all(6),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(8)),
                                  child: AssetThumb(
                                    asset: asset,
                                    width: 600,
                                    height: 600,
                                  ),
                                );
                              }),
                            ),
                          )
                        ],
                      )
                    : Container()
              ],
            ),
            
              ],
            ),
            SizedBox(
              height: 25,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CustomButton2(
                  onPressed: () {
                    submit();
                  },
                  text: "SAVE & NEXT",
                  textStyle: boldRedTitle().copyWith(color: Colors.white),
                  gradient: buttongradient,
                ),
              ],
            ),
            SizedBox(
              height: 30,
            )
          ],
        ),
      ),
    );
  }

  submit() {
    print("1" + _selectedIdProof.toString());

    Business? business = Business();
    print("33" + jsonEncode(business).toString());
    business.bank!.bankName = _selectedIdProof.toString();

    print("11");
    print(business.bank!.bankName.toString());
    print(jsonEncode(business.bank!.bankName));
    print("22");
    Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => BusinessRegistration(
              index: 2,
              businessData: business,
            )));
  }
}

This is a my business model


import 'package:evillage_app/models/business/bank/bank.dart';
import 'package:evillage_app/models/business/hours/hours.dart';
import 'package:evillage_app/models/business/proof/proof.dart';
import 'package:evillage_app/models/utils/attachment/attachment.dart';
import 'package:evillage_app/models/utils/map/map.dart';
import 'package:json_annotation/json_annotation.dart';
part 'business.g.dart';
@JsonSerializable()
class Business {

   String? id;
   String? name;
   String? contact;
   String? website;
   String? address;
   String? landmark;
   String? area;
   String? pincode;
   String? country;
   String? state;
   String? district;
   String? tehsil;
   String? villagePanchayat;
   MapModel? map;
   String? category;
   String? aboutShop;
   String? minimumPurchase;
   Proof? idProof;
   Proof? panProof;
   Proof? addressProof;
   Proof? gst;
   Proof? registrationCertificate;
   Bank? bank;
   List<String>? upi;
   List<Hours>? hours;
   List<Attachment>? media;
   Attachment? logoMedia;
   bool? status;


  factory Business.fromJson(Map<String, dynamic> json) =>
      _$BusinessFromJson(json);

  Business(
      { this.id,
      this.name,
      this.contact,
      this.website,
      this.address,
      this.landmark,
      this.area,
      this.pincode,
      this.country,
      this.state,
      this.district,
      this.tehsil,
      this.villagePanchayat,
      this.map,
      this.category,
      this.aboutShop,
      this.minimumPurchase,
      this.idProof,
      this.panProof,
      this.addressProof,
      this.gst,
      this.registrationCertificate,
      this.bank,
      this.upi,
      this.hours,
      this.media,
      this.logoMedia,
      this.status});

  Map<String, dynamic> toJson() => _$BusinessToJson(this);
}

This is my Bank model


import 'package:json_annotation/json_annotation.dart';

part 'bank.g.dart';

@JsonSerializable()
class Bank {
   String? bankName;
   String? branchName;
   String? type;
   String? accountNumber;
   String? ifscCode;
   String? micrCode;
   String? beneficiaryName;

  factory Bank.fromJson(Map<String, dynamic> json) => _$BankFromJson(json);

  Bank(
      {this.bankName,
      this.branchName,
      this.type,
      this.accountNumber,
      this.ifscCode,
      this.micrCode,
      this.beneficiaryName});

  Map<String, dynamic> toJson() => _$BankToJson(this);
}

Deepak
  • 1,664
  • 3
  • 19
  • 52

1 Answers1

1

Dart is helping you finding such error! That's why sound null safety exists. Dart is saying: you're trying to evaluate something onto a null value (and it usually tells you where this problem occurs).

In your case, this happens because your Business() Object has a Bank? bank property which is nullable by definition (the ? operator marks it).

Your submit() method instantiates an empty Business(), by default your constructor will fill bank with a null value. When you try to access it here:

business.bank!.bankName = _selectedIdProof.toString();

You're forcing Dart to call a bankName property on bank, but bank is null, so Dart returns you an exception.

You should either improve code quality by removing null values - unless it makes sense for your business logic - or just avoid using the null check operator ! which is something that should be used if you're 100% sure that such value isn't null. PREFER using the ? null-aware operators, such as ?., ??, ??=. etc.

esentis
  • 4,190
  • 2
  • 12
  • 28
venir
  • 1,809
  • 7
  • 19