skip to Main Content

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?

2

Answers


  1. Details? oneUserDetails;

    Change this to:

      Details oneUserDetails = Details();
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search