Home > Mobile >  How to resolve Null check operator used on a null value on flutter?
How to resolve Null check operator used on a null value on flutter?

Time:11-03

I tried to fetch data from the subcollection using a logged user ID. Then display this error enter image description here

I tried to fetch it from the firestore sub-collection.The collection name is "users" and doc name is userid

code

Future<void> getAmount() async {
    final id = "${loggedInUser.uid}";
    final reference = FirebaseFirestore.instance.doc('users/$id/recharge/$id');
    final snapshot = reference.get();

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

text widget

Text(
            oneAmount!.amount,
            style: GoogleFonts.roboto(
              textStyle: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: kWhite,
              ),
            ),

model

import 'dart:convert';

Amounts articlesFromJson(String str) => Amounts.fromJson(json.decode(str));

String articlesToJson(Amounts data) => json.encode(data.toJson());

class Amounts {
  Amounts({
    required this.id,
    required this.amount,
  });
  String id;
  String amount;

  factory Amounts.fromJson(Map<String, dynamic> json) => Amounts(
        id: json["id"] ?? "",
        amount: json["amount"] ?? "",
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "amount": amount,
      };
}

CodePudding user response:

Instead of using ! you can accept null value like

Text("${oneAmount?.amount}"),

Or provide default value on null case

Text(oneAmount?.amount?? "got NUll"),

or do a null check then show widget

if(oneAmount!=null) Text(oneAmount.amount),
  • Related