【问题标题】:How to check if array is null and display not available if it's null如何检查数组是否为空,如果为空则显示不可用
【发布时间】:2021-06-09 10:51:39
【问题描述】:

不幸的是,我的控制台显示“在 null 上调用了方法 '[]'。”当我尝试在 Firestore 中显示产品没有以下数组作为选项的产品页面时出错。有没有办法检查数组是否有空值并在它不在 Firestore 时显示“产品个性化不可用”。当 productPersonalisation 列表可用时,以下代码可以正常工作。

import 'package:fj_trade/constants.dart';
import 'package:flutter/material.dart';

class ProductPersonalisation extends StatefulWidget {


  final List productPersonalisation;
  final Function(String) onSelected;



  const ProductPersonalisation({Key key, this.productPersonalisation, this.onSelected}) : super(key: key);

  @override
  _ProductPersonalisationState createState() => _ProductPersonalisationState();
}

class _ProductPersonalisationState extends State<ProductPersonalisation> {

  int _selected = 0;


  @override
  Widget build(BuildContext context) {
    return Row(
      children: [


        for(var  i=0; i < widget.productPersonalisation.length; i++)
          GestureDetector(
            onTap: () {
              widget.onSelected("${widget.productPersonalisation[i]}");
              setState(() {
                _selected = i;
              });
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 0.0),
              height: 42,
              decoration: BoxDecoration(
                color: _selected == i ? Theme.of(context).accentColor : Constants.lightGrey,
                borderRadius: BorderRadius.circular(4),
              ),
              alignment: Alignment.center,
              margin: EdgeInsets.only(
                right: 6.0,
              ),
              child: Text("${widget.productPersonalisation[i]}",
                style: TextStyle(
                  fontWeight: FontWeight.w600,
                  color: _selected == i ? Colors.white : Colors.black87,
                ),
              ),
            ),
          ),
      ],
    );
  }
}

【问题讨论】:

  • widget.productPersonalisation == null //如果为null则返回true widget.productPersonalisation.isEmpty //如果List中没有item且List不为空则返回true跨度>

标签: arrays firebase flutter dart arraylist


【解决方案1】:

如果数组中的元素为空,则可以这样做

widget.onSelected("${widget.productPersonalisation[i] ?? 'Product Personalisation Not Available'}");

但是在循环之前,您应该检查 widget.productPersonalisation 不为空。

【讨论】:

    【解决方案2】:

    如果您尝试访问空列表的索引,它将引发异常。 试试这个:

    widget.onSelected(widget.productPersonalisation != null ? "${widget.productPersonalisation[i]}" : 'Product Personalisation Not Available');
    

    【讨论】:

      猜你喜欢
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      相关资源
      最近更新 更多