2

this error :

Null check operator used on a null value

happens when we use bang operator (!) on a nullable instance which wasn't initialized.

   class Wallet_Page extends StatefulWidget {
  @override
  State<Wallet_Page> createState() => _Wallet_PageState();
}

class _Wallet_PageState extends State<Wallet_Page> {
  TextEditingController _increaseBalance_Cotroller = TextEditingController();

  List<TextEditingController> _buyCrypto_Cotroller =
      List.generate(100, (i) => TextEditingController());

  List<TextEditingController> _sellCrypto_Cotroller =
      List.generate(100, (i) => TextEditingController());

  getCryptoData data = getCryptoData();

  String? _currentUser;
  Map? _userData;

  String? userName;
  String? userLastName;
  double? userFiatAsset;

  List cryptoName = <String>[];
  List cryptoSymbol = <String>[];
  List cryptoPrice = <double>[];
  List cryptoLogo = <String>[];

  List cryptoAsset = <double>[];

  int _selectedIndex = 0;
  Future<void> getUserData() async {

    _currentUser = await FirebaseAuth.instance.currentUser!.email.toString();
    print(_currentUser);

    await FirebaseFirestore.instance
        .collection('users')
        .doc(_currentUser)
        .get()
        .then((value) => {_userData =  value.data()});

    print(_userData);
   
    if (_userData != null) {
      print((_userData ?? {"": ""})['Name']);
      print((_userData ?? {"": ""})['LastName']);
      print((_userData ?? {"": ""})['FiatAsset']);

      //userName = (_userData ?? {"":""})['Name'];
      userLastName  = (_userData ?? {"":""})['LastName'];
      userFiatAsset = (_userData ?? {"":""})['FiatAsset'];
    }

  }

  Future<void> getData() async {
    await data.getData();
    for (var i = 0; i < data.cryptoName.length; i++) {
      cryptoName.insert(i, data.cryptoName[i]);
      cryptoSymbol.insert(i, data.cryptoSymbol[i]);
      cryptoPrice.insert(i, data.cryptoPrice[i]);
      cryptoLogo.insert(i, data.cryptoLogo[i]);
      //cryptoAsset.insert(i, 0.0);
      
       // if( _userData![cryptoSymbol[i]] != null){
       //   cryptoAsset.insert(i, _userData![cryptoSymbol]);
       // }else
       //   {
       //     cryptoAsset.insert(i, 0);
       //   }

    }
  }


  @override
  initState() {
    super.initState();
    getUserData().then((value) => setState(() {}));
    getData().then((value) => setState(() {}));
    //getData();
  }
  

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: Theme(
        data: Theme.of(context).copyWith(
          canvasColor: Colors.black,
        ),
        child: SizedBox(
          height: 50,
          child: BottomNavigationBar(
            currentIndex: _selectedIndex,
            onTap: _onTap,
            unselectedItemColor: textColor,
            unselectedIconTheme: IconThemeData(color: textColor),
            selectedItemColor: Colors.indigo.shade600,
            items: [
              BottomNavigationBarItem(
                icon: Icon(
                  Icons.logout,
                  size: 20,
                  //color: textColor
                ),
                label: "Logout",

              ),
              BottomNavigationBarItem(
                  icon: Icon(
                    Icons.currency_bitcoin_sharp,
                    size: 20,
                    //color: textColor,
                  ),
                  label: "Crypto Asset"),
            ],
          ),
        ),
      ),
      backgroundColor: scaffold_color,
      body: SafeArea(
        child: Center(
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Container(
                  width: MediaQuery.of(context).size.width * 0.9,
                  height: MediaQuery.of(context).size.height * 0.25,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        stops: [0.2, 0.8],
                        colors: [Colors.black54, Colors.indigo.shade800]),
                  ),
                  child: userName != null
                      ? Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Text(
                              "Hi ${userName}! 🧡",
                              style: GoogleFonts.lato(
                                textStyle: TextStyle(
                                  color: textColor,
                                  fontSize: 25,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                            Text(
                              " welcome to CryptoWallet! ",
                              style: GoogleFonts.lato(
                                textStyle: TextStyle(
                                  color: textColor,
                                  fontSize: 25,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                              child: Text(
                                " Your balance: ",
                                style: GoogleFonts.lato(
                                  textStyle: TextStyle(
                                    color: textColor,
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ),
                            Center(
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Icon(
                                    Icons.attach_money,
                                    size: 50,
                                    color: Colors.deepOrange,
                                  ),
                                  Text(
                                    userFiatAsset!.toStringAsFixed(2),
                                    style: GoogleFonts.lato(
                                      textStyle: TextStyle(
                                        color: textColor,
                                        fontSize: 50,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.only(left: 15),
                                    child: CircleAvatar(
                                      radius: 18,
                                      backgroundColor: addButtonColor,
                                      child: IconButton(
                                        onPressed: IncreaseBalance,
                                        icon: Icon(
                                          Icons.add,
                                          color: textColor,
                                          size: 20,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        )
                      : Center(child: CircularProgressIndicator()),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Container(
                      width: MediaQuery.of(context).size.width * 0.9,
                      height: MediaQuery.of(context).size.height * 0.8,
                      child: cryptoName.length == 100
                          ? ListView.builder(
                              itemCount: cryptoName.length,
                              itemBuilder: (BuildContext, index) {
                                return CryptoCard(
                                  name: cryptoName[index],
                                  logo: cryptoLogo[index],
                                  symbol: cryptoSymbol[index],
                                  price: cryptoPrice[index],
                                  //asset: cryptoAsset[index],
                                  onPressed_sell: () {
                                    onPressed_sell(index);
                                  },
                                  onPressed_buy: () {
                                    //print(index);
                                    onPressed_buy(index);
                                  },
                                  //symbol:cryptoSymbol[index],
                                );
                              })
                          : Center(
                              child: CircularProgressIndicator(),
                            )),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

when I perform this the mentioned error pops up. when I comment the line

userName = _userData!['Name'];

the error is solved, so I understand that the error is from this line.. but my previous prints work well and return the desire value:

print(_userData!['Name']);

so how can this happen? I have a valuable that is not null but the error shows something else.. what is wrong?

2 Answers 2

1

Try the following code:

  String? _currentUser;
  Map? _userData;

  String? userName;
  String? userLastName;
  double? userFiatAsset;


  List cryptoAsset = <double>[];
  Future<void> getUserData() async {

    _currentUser = await FirebaseAuth.instance.currentUser!.email.toString();
    print(_currentUser);

    await FirebaseFirestore.instance
        .collection('users')
        .doc(_currentUser)
        .get()
        .then((value) => _userData =  value.data());

    if (_userData != null) {
      print((_userData ?? {*the value you want to replace when returning null to you})['Name']);
      print((_userData ?? {*the value you want to replace when returning null to you})['LastName']);
      print((_userData ?? {*the value you want to replace when returning null to you})['FiatAsset']);

       userName = (_userData ?? {*the value you want to replace when returning null to you})['Name'];
       userLastName = (_userData ?? {*the value you want to replace when returning null to you})['LastName'];
       userFiatAsset = (_userData ?? {*the value you want to replace when returning null to you})['FiatAsset'];

    }
  }
Sign up to request clarification or add additional context in comments.

7 Comments

thanks, I tested it but it continues to pop up the same error! but when I comment the line "userName = (_userData ?? {"":""})['Name'];" the error is solved! I cant find the reason! there is no null operator "!" there in the line!
Where are you using userName?
I edited the code and posted more details of it. I used the userName in a Text widget in a column.. I've also searched the usage of this variable(userName) and there is no other place I used it
Can you show the line you commented on?
I edited the post, again. in this version I have no error! because I have commented it in the getUserData() funciton. when I uncomment this to do its job, the error pops up.
|
1

remove ?, it explicitly states that a variable/parameter may be null.

String _currentUser;
Map _userData;
String userName;
String userLastName;
double userFiatAsset;

You can use late keyword when your parameters will be assigned soon:

late Map _userData;

When you use ! it means conversion from a nullable to a non-nullable type. Use it only if you are absolutely sure that the value will never be null. You can remove ! it when your sure its not null

userName = _userData['Name'];

BTW, you check for userData, which means it wont be null

if (_userData != null) {} // this condition is enough for this

null safety in dart

You can also use ?? when it returns null assign new value to it:

_userData['Name'] ?? // value when its null

what-is-the-dart-null-checking-idiom

3 Comments

mamnoon dadash manam az Iranam... thank you but when I remove "?" from Map? _userData I get the error: Non-nullable instance field '_userData' must be initialized and also when I remove "!" from _userData!['Name'] I get the error: The method '[]' can't be unconditionally invoked because the receiver can be 'null'. (Documentation) '_userData' refers to a property so it couldn't be promoted. Try making the call conditional (using '?.') or adding a null check to the target ('!').
XD ,ok use ?? after _userData!['Name'] to pass default value to it
thankks , but it did not solved the error! I dont know why it should be such an error while there is no "!" oeprator!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.