arrays - Flutter:如何将数组数据从 json Future< 传递到 Widget
问题描述
作为 Flutter 的新手,我正在学习并在旅途中磕磕绊绊。
我正在尝试将从 json 收到的数组传递到已经等待的小部件结构中,但似乎无法获得连接。
这是示例代码:
class Products extends StatefulWidget {
@override
_ProductsState createState() => _ProductsState();
}
class _ProductsState extends State<Products> {
@override
void initState() {
_getProducts();
}
Future<List<Single_prod>> _getProducts() async {
var url = "";
var data = await http.get(url);
var jsonData = json.decode(data.body) as Map<String, dynamic>;
//print(jsonData.toString());
//jsonData.forEach((k, v) => print("Key : $k, Value : $v"));
List<Single_prod> items = [];
jsonData.forEach((k, v){
Single_prod item = Single_prod(v["error"], v["id"], v["name"], v["price"], v["image"]);
items.add(item);
});
//print(items.length);
return items; <---Tring to pass this to Widget build but not recognized.....
}
@override
Widget build(BuildContext context) {
return GridView.builder(
itemCount: items.length,
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (BuildContext context, int index){
return Single_prod(
prod_err: items[index]['error'], <--- This items array is not recognized
prod_id: items[index]['id'],
prod_name: items[index]['name'],
prod_price: items[index]['price'],
prod_image: items[index]['image'],
);
});
}
}
小部件中无法识别项目数组
这是其余的代码:
class Single_prod extends StatelessWidget {
final prod_err;
final prod_id;
final prod_name;
final prod_price;
final prod_image;
Single_prod({
this.prod_err,
this.prod_id,
this.prod_name,
this.prod_price,
this.prod_image,
});
@override
Widget build(BuildContext context) {
return Card(
child: Hero(
tag: prod_name,
child: Material(
child: InkWell(
onTap: () => Navigator.of(context).push(new MaterialPageRoute(
// here we are passing the values of the products to the details page
builder: (context) => new ProductDetails(
prod_detail_name: prod_name,
prod_detail_image: prod_image,
prod_detail_id: prod_id,
prod_detail_price: prod_price,
))),
child: GridTile(
footer: Container(
height: 40.0,
color: Colors.white70,
child: ListTile(
leading: Text(prod_name, style: TextStyle(fontWeight: FontWeight.bold),),
title: Text(
prod_price,
style: TextStyle(color: Colors.blue, fontWeight: FontWeight.w800, fontSize: 12),
),
/*subtitle: Text(
prod_oldprice,
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w800, fontSize: 11, decoration: TextDecoration.lineThrough),
),*/
),
),
child: Image.asset(prod_image,
fit: BoxFit.cover,),
),
),
),
),
);
}
}
上层代码与下层代码如何连接?提前致谢。
解决方案
首先,查看“items”变量的范围:它在 getItems() 函数中定义,并且在函数之外不可见。所以,第一件事:使它成为类级别的属性。
接下来 - 您的 initState 将调用您的方法。方法是异步的,并且在 initState 中处理它的方式是在您的方法返回的 Future 上使用“.then”。你在这里要做的是:一旦未来完成,你想设置你的类级变量来保存 _getProduct() 函数返回的值。
最后——理解这一点非常重要:你自己不会调用 build 方法——flutter 框架会为你做这件事。现在,flutter 没有一种神奇的方式来知道您何时更改了数据 - 它不会观察您的代码,因此您需要以某种方式告诉它您的状态对象已更改,并且需要重建。您可以通过调用 setState() 函数来完成。
我认为您实际上还有另一个问题:您已经在 _getProduct() 中构建了 Single_prod 小部件,无需再次构建它。我也试图纠正这一点。
试试这个(我没有编译它,所以它可能有一些错误):
class Products extends StatefulWidget {
@override
_ProductsState createState() => _ProductsState();
}
class _ProductsState extends State<Products> {
List<Single_prod> items = [];
@override
void initState() {
super.initState();
_getProducts().then( (result) {
setState(() {
items=result;
}
});
}
Future<List<Single_prod>> _getProducts() async {
var url = "";
var data = await http.get(url);
var jsonData = json.decode(data.body) as Map<String, dynamic>;
//print(jsonData.toString());
//jsonData.forEach((k, v) => print("Key : $k, Value : $v"));
List<Single_prod> items = [];
jsonData.forEach((k, v){
Single_prod item = Single_prod(v["error"], v["id"], v["name"], v["price"], v["image"]);
items.add(item);
});
//print(items.length);
return items;
}
@override
Widget build(BuildContext context) {
return GridView.builder(
itemCount: items.length,
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (BuildContext context, int index){
return items[index];
});
}
}
推荐阅读
- node.js - 这个oracle查询的芒果等价物是什么
- python - Pandas 以多列爆炸(不同的嵌套列表长度)
- asp.net-web-api - 使用 web api 发布文件时,我收到“消息:发生错误”但它不执行 catch
- ios - Firebase 动态链接在应用程序中打开我的所有域链接
- mysql - 当字符串是使用 MySQL 的表中另一列中的数据时,如何在表的一列中搜索字符串
- python - python中的数组选择
- annotations - Struts 2 post back 默认
- python - Python Typeerror:所有中间步骤都应该是转换器并实现拟合和转换
- xml - 如何计算 XSLT 1.0 中每个单元分组的节点总和?
- string - 匹配不同长度的字符串前缀