我正尝试在Flutter中构建动态UI。我正在从REST API获得快餐位置,并希望为返回的每个位置创建一个card
。
为此,我创建了此类:
class LocationCard extends StatelessWidget
{
FFLocation location;
@override
Widget build(BuildContext context)
{
return new Container(
child: Card(
child: Row(
children: <Widget>[
Image.asset("shoppingcart.png"),
Column(children: <Widget>[
Text(location.name),
Text(location.streetNumber + " " + location.street + " " + location.city),
],),
],
)
)
);
}
}
然后,在主页上,我想将每个位置添加到ListView中。我尝试这样做:
new ListView(
children: <Widget>[
new FutureBuilder<List<FFLocation>>
(
future: ApiDAO.GetLocationsFromLatLong(),
builder: (BuildContext context, AsyncSnapshot<List<POPLocation>> snapshot)
{
switch (snapshot.connectionState)
{
case ConnectionState.waiting:
return Text("Loading Locations...");
case ConnectionState.none:
return Text("No locations nearby!");
default:
if (snapshot.hasError)
{
return Text("There was an error: ${snapshot.error}");
} else {
if (snapshot.hasData)
{
if (snapshot.data != null)
{
snapshot.data.forEach((currentLocation)
{
LocationCard card = new LocationCard();
card.location = currentLocation;
//return card.build(context);
var temp = card.build(context);
return temp;
});
}
}
}
}
},
)
],
),
将哪个数据从API返回,并尝试将每个数据制作为小部件。但是,即使创建了一个位置和一个位置小部件,它也不会显示。有什么我误会的东西,或者更简单的方法吗?
我还应该注意,我遇到了这个异常:
A build function returned null.
The offending widget is: FutureBuilder<List<FFLocation>>
答案 0 :(得分:1)
只需进行一些更改即可使其生效:
@override
Widget build(BuildContext context) {
return Container(
child: new FutureBuilder<List<FFLocation>>(
future: ApiDAO.GetLocationsFromLatLong(),
builder:
(BuildContext context, AsyncSnapshot<List<FFLocation>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text("Loading Locations...");
case ConnectionState.none:
return Text("No locations nearby!");
default:
if (snapshot.hasError) {
return Text("There was an error: ${snapshot.error}");
} else {
if (snapshot.hasData) {
if (snapshot.data != null) {
return ListView.builder(
itemBuilder: (context, index) {
LocationCard card = new LocationCard();
card.location = snapshot.data[index];
//return card.build(context);
var temp = card.build(context);
return temp;
},
itemCount: snapshot.data.length,
);
}
}
}
}
}),
);
}