0

我正在制作一个“食谱应用程序”来学习。我现在遇到了这个问题:
我正在使用 Sqflite,我有一个页面显示配方中的成分,sql 查询没问题,但问题是我得到的是空值而且我不知道怎么做才能隐藏它们。我已经尝试过条件、运算符(例如(条件?X:Y))、替换,但似乎没有任何效果。PS:有些变量是西班牙语,因为我说的是那种语言。

成分型号:

class IngredienteModel {
  IngredienteModel(
      {this.idIngrediente,
      this.idListaIngredientes,
      this.amount,
      this.unit,
      this.name});

  int? idIngrediente;
  int? idListaIngredientes;
  String? amount;
  String? unit;
  String? name;

  factory IngredienteModel.fromJson(Map<String, dynamic> json) =>
      IngredienteModel(
          idIngrediente: json["id_ingrediente"],
          idListaIngredientes: json["id_lista_ingredientes"],
          amount: json["amount"],
          unit: json["unit"],
          name: json["name"]);

  Map<String, dynamic> toJson() => {
        "id_ingrediente": idIngrediente,
        "id_lista_ingredientes": idListaIngredientes,
        "amount": amount,
        "unit": unit,
        "name": name,
      };
}

我返回要显示的成分的小部件:

List<Widget> ingredientesList(
    List<IngredienteModel>? ingredientes, BuildContext context) {
  final List<Widget> _listaIng = [];
  int _index = 1;
  ingredientes!.forEach((element) {
    final _widgetTemp = Row(
          children: [
            Text(_index.toString() + ": "),
            Text(element.amount.toString() + " "),
            _unitText(element),
            Text(element.name.toString()),
          ],
        );
    _listaIng.add(_widgetTemp);
    _index = _index + 1;
  });

  return _listaIng;
}
 
Widget _unitText(IngredienteModel ingmod) {
  if (ingmod.unit?.isEmpty) {
    return Text(" ");
  } else {
    return Text(ingmod.unit + " de ");
  }
}
 

在最后一种方法中_unitText,我尝试了很多方法来施展魔法,但是:

-我不能在条件中使用“ingmod.unit?.isEmpty”,因为:

A nullable expression can't be used as a condition. Try checking that the value isn't 'null' before using it as a condition.

- 不能使用“ingmod.unit.length == 0”,因为: The property 'length' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!').

-然后,要返回不为空的“成分单元文本”,我不能使用“+”添加字符串: "The operator '+' can't be unconditionally invoked because the receiver can be 'null'. Try adding a null check to the target ('!').

如果我修复错误以运行应用程序,我会得到这个(如您所见,空值是可见的):

1

4

1 回答 1

0

尝试在 fromJson 方法的所有字段中放置

json [variable] ?? DEFAULT VALUE

它的作用是,如果该变量不在 json 中,则默认设置该值

于 2021-09-26T16:31:37.370 回答