flutter - 空检查运算符用于 flutter、dart 中的空值

标签 flutter dart null

这个错误:

Null check operator used on a null value

当我们在未初始化的可为 null 的实例上使用 bang 运算符 (!) 时,就会发生这种情况。

   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(),
                            )),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

当我执行此操作时,会弹出上述错误。当我评论该行时

userName = _userData!['Name'];

错误已解决,所以我知道错误来自这一行..但我之前的打印效果很好并返回所需的值:

print(_userData!['Name']);

怎么会发生这种情况呢?我有一个不为空的值,但错误显示了其他内容..出了什么问题?

最佳答案

尝试以下代码:

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

    }
  }

关于flutter - 空检查运算符用于 flutter、dart 中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73923566/

相关文章:

dart - 我可以从 json 字符串创建一个 const 对象吗?

java - null 参数的 IllegalArgumentException 或 NullPointerException?

listview - rxdart replaySubject 流到 listview 中

java - 重复类 com.google.android.exoplayer2.ui.DownloadNotificationHelper

dart - 我现有项目中使用的 dart 版本

flutter - flutter 中的柔性容器

c++ - 空格与空字符

java - WeakHashMap 的 keySet 条目永远不会为空吗?

animation - flutter 支持动画 svg 吗?

flutter - 在其他页面打开抽屉