flutter如何解决"A non-null String must be provided to a Text widget"错误?

码云
2020-11-19 09:20

使用Text控件的时候报错:A non-null String must be provided to a Text widget原因在于Text的内容不能为空,可以对变量赋予一个默认值或者检查变量值是否为null,如果是则采用默认值。参考以下代码:

Container(
        height: 60,
        width: 60,
        padding: EdgeInsets.only(left: 10),
        child: Column(
          children: <Widget>[
            new GestureDetector(child: Icon(Icons.arrow_drop_up), onTap: () {}),
            new Text(cart_prod_qty),
            new GestureDetector(child: Icon(Icons.arrow_drop_down), onTap: () {})
          ],
        ),
//上面的new Text(cart_prod_qty)中cart_prod_qty的值如果为null则会报错

//使用下面的方式可以避免产生该错误
Container(
        height: 60,
        width: 60,
        padding: EdgeInsets.only(left: 10),
        child: Column(
          children: <Widget>[
            new GestureDetector(child: Icon(Icons.arrow_drop_up), onTap: () {}),
            Text(cart_prod_qty??'default value'), //注意
            new GestureDetector(child: Icon(Icons.arrow_drop_down), onTap: () {})
          ],
        ),

 

全部评论