Home > Enterprise >  When before the open page show "Null check operator used on a null value" and after fetch
When before the open page show "Null check operator used on a null value" and after fetch

Time:12-27

In my code fetch data and show nicely but before open the that page show this error and after show those details.In my code fetch data from firebase array type data and string type data.

error

enter image description here

after that error page opening and fetch data prefect

enter image description here

model code

class Details {
  String? id;
  String? email;
  String? age;
  String? familyChildren;
  List<String>? drinkstalkSE;
  List<String>? drinksUnderstandSE;
  List<String>? drinksUnderstandSE2;

  Details(
      {this.id,
      this.email,
      this.age,
      this.familyChildren,
      this.drinkstalkSE,
      this.drinksUnderstandSE,
      this.drinksUnderstandSE2});

  Details.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    email = json['email'];
    age = json['age'];
    familyChildren = json['familyChildren'];
    drinksUnderstandSE = json['drinksUnderstandSE'].cast<String>();
    drinkstalkSE = json['drinkstalkSE'].cast<String>();
    drinksUnderstandSE2 = json['drinksUnderstandSE2'].cast<String>();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['email'] = this.email;
    data['age'] = this.age;
    data['familyChildren'] = this.familyChildren;

    data['drinksUnderstandSE'] = this.drinksUnderstandSE;
    data['drinkstalkSE'] = this.drinkstalkSE;
    data['drinksUnderstandSE2'] = this.drinksUnderstandSE2;
    return data;
  }
}

backend code

 Details oneUserDetails = Details();
  Future<void> getDetails() async {
    final sp = context.read<SignInProvider>();

    print(sp.uid);
    final snapshot =
        FirebaseFirestore.instance.collection('users').doc('${sp.uid}').get();

    final result = await snapshot.then(
        (snap) => snap.data() == null ? null : Details.fromJson(snap.data()!));
    print('result is ====> $result');
    setState(() {
      oneUserDetails = result!;
      loading = false;
    });

How to remove that error showing before the page open?

CodePudding user response:

oneUserDetails is defines as nullable variable and its may be null but you use ! in Text widget when try to access drinksUnderstandSE or other property which is wrong because by using ! you said I'm pretty sure it is not null which it is, so change ! to ?:

Text( 'drink understand : ${oneUserDetails?.drinksUnderstandSE}'), // this will show like this => drink understand : null

or you can set default value to avoid showing null, like this:

Text( 'drink understand : ${oneUserDetails?.drinksUnderstandSE ?? 'default variable'}'), // this will show like this => drink understand : default variable

CodePudding user response:

Details? oneUserDetails;

Change this to:

  Details oneUserDetails = Details();
  • Related