我有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"
}
]
我使用TableRow
在Table
中显示“大陆”和“国家”,
TableRow(children: [
TableCell(child: Text(continent.continent)),
TableCell(child: Text(continent.country))])
但是如果List或continent.country == null
中没有“国家”,则不希望显示TableRow
,所以请帮我设置条件:
这是主文件:
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))]),
]),
),
],
),
);
}
}
尝试添加带有空子项的TableRow
。
continent.country == null
? TableRow(children: [])
: TableRow(children[
TableCell(child: Text(continent.continent)),
TableCell(child: Text(continent.country))
]),
如果升级到最新的Flutter SDK(Dart 2.3),则可以使用简单的if语句有条件地呈现TableRow或任何其他小部件。
...
If(continent.country != null)
TableRow(children: [
TableCell(child: Text(continent.continent)),
TableCell(child: Text(continent.country))]),
]
如果没有,请尝试使用此软件包: