我正在构建一个连接并将请求发送到HTTP服务器的应用程序,并在获取响应时将它们解析为JSON对象并显示输出。当我使用以下方法时会发生此问题:
Future<List<Widget>> getPizzas() async {
List<Widget> pizzasElements;
await PizzeriaAPI().getMenu().then((response) {
Iterable list = json.decode(response.body);
var pizzas = list.map((model) => Pizza.fromJson(model)).toList();
pizzasElements =new List<Widget>.generate(pizzas.length, (int index){
Row row = new Row();
row.children.add(new Text(pizzas[index].name));
row.children.add(new Text("${pizzas[index].price} \$"));
row.children.add(new MaterialButton(color: Colors.green,child: Text("Add"),onPressed: (){
// esegui il post
}));
return row;
});
});
}
这是构建方法:
@override
Widget build(BuildContext context) {
getPizzas().then((List<Widget> response){
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.dark,
),
home: DefaultTabController(length: 4, child: Scaffold(
appBar: AppBar(
title: const Text('Pizzeria'),
bottom: TabBar(
isScrollable: true,
tabs: [
Tab(text: "Buy"),
Tab(text: "Orders"),
Tab(icon: Icon(Icons.shopping_cart)),
Tab(icon: Icon(Icons.settings))
]
),
),
body: TabBarView(children: [
Column(
children: response,
),
Column(
children: <Widget>[
Row(
children: <Widget>[
Text("Orders")
],
)
],
),
Column(
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.shopping_cart)
],
)
],
),
Column(
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.settings)
],
)
],
)
]),
)
)
);
}
);
}
}
我获得了一个Future Object而不是List Object。 用于显示元素的代码是:
Column(
children: response,
),
如何从此方法获取List并显示输出?
问题是getPizzas()
是异步的,这意味着它返回一个Future
。您需要的内容本质上意味着您应该将渲染代码更改为:
Column(
children: pizzasElements,
),
因为您似乎将pizzaElements
设置为包含您的小部件列表。
您需要做的是将构建方法与请求分开。所以在你的构建函数中,只需调用getPizzas()
函数并忘记它。像这样:
Widget build(BuildContext context) {
getPizzas();
return MaterialApp(...
接下来,您需要确保pizzaElements
已初始化并且是类属性而不是局部变量。所以这意味着你需要使用StatefulWidget
,这将发生在State类中。
List<Widget> pizzaElements = <Widget>[];
然后在getPizzas()
中,您需要确保调用setState
以便使用列表重新呈现您的小部件:
void getPizzas() {
PizzeriaAPI().getMenu().then((response) {
Iterable list = json.decode(response.body);
var pizzas = list.map((model) => Pizza.fromJson(model)).toList();
setState(() {
pizzasElements = new List<Widget>.generate(pizzas.length, (int index) {
Row row = new Row();
row.children.add(new Text(pizzas[index].name));
row.children.add(new Text("${pizzas[index].price} \$"));
row.children.add(new MaterialButton(
color: Colors.green,
child: Text("Add"),
onPressed: () {
// esegui il post
}));
return row;
});
});
});
}