Flutter:如果值为null或没有值,如何隐藏TableRow

问题描述 投票:0回答:2

我有2种JSON情况,如下所示

情况1:“国家/地区的一个值为空

[
  {
    "id": 1,
    "continent": "North America",
    "country": "United States"
  },
  {
    "id": 2,
    "continent": "Europe",
    "country": "Germany"
  },
  {
    "id": 3,
    "continent": "Asia",
    "country": null
  }
]

情况2:“国家/地区”之一没有价值

[
  {
    "id": 1,
    "continent": "North America",
    "country": "United States"
  },
  {
    "id": 2,
    "continent": "Europe",
    "country": "Germany"
  },
  {
    "id": 3,
    "continent": "Asia"
  }
]

我使用TableRowTable中显示“大陆”和“国家”,

TableRow(children: [
                      TableCell(child: Text(continent.continent)), 
                      TableCell(child: Text(continent.country))])

但是如果List或continent.country == null中没有“国家”,则不希望显示TableRow,所以请帮我设置条件:

  1. 案例1
  2. 案例2
  3. 案例1 +案例2

这是主文件:

import 'package:ask/services/continent_services2.dart';
import 'package:flutter/material.dart';
import 'model/continent_model2.dart';

class TableRowDemo extends StatefulWidget {
  TableRowDemo() : super();

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

class _ContinentPageState extends State<TableRowDemo> {
  List<Continent> _continent;

  @override
  void initState() {
    super.initState();

    ContinentServices2.getContinent().then((continents) {
      setState(() {
        _continent = continents;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('')),
      body: Column(
        children: <Widget>[
          for (Continent continent in _continent)
            SingleChildScrollView(
              child: Table(children: [
                continent.country == null
                    ? Container() // Error: type 'Container' is not a subtype of type 'TableRow'
                    : TableRow(children: [
                      TableCell(child: Text(continent.continent)),
                      TableCell(child: Text(continent.country))]),
              ]),
            ),
        ],
      ),
    );
  }
}

flutter dart
2个回答
0
投票

尝试添加带有空子项的TableRow

continent.country == null 
    ? TableRow(children: []) 
    : TableRow(children[
        TableCell(child: Text(continent.continent)),
        TableCell(child: Text(continent.country))
      ]),

0
投票

如果升级到最新的Flutter SDK(Dart 2.3),则可以使用简单的if语句有条件地呈现TableRow或任何其他小部件。

...
If(continent.country != null)
     TableRow(children: [
          TableCell(child: Text(continent.continent)),
          TableCell(child: Text(continent.country))]),
              ]

如果没有,请尝试使用此软件包:

https://pub.dev/packages/flutter_conditional_rendering

© www.soinside.com 2019 - 2024. All rights reserved.