Eric Matevosian
Eric Matevosian

Reputation: 145

Null check operator used on a null value in flutter,dart

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?

Upvotes: 2

Views: 2710

Answers (2)

mohammad esmaili
mohammad esmaili

Reputation: 1747

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

Upvotes: 1

My Car
My Car

Reputation: 4566

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'];

    }
  }

Upvotes: 1

Related Questions