我有json文件,我想在容器中显示它。我尝试了很多事情,但是没有任何效果。现在,我有这个error
我已经尝试过使用jsonDecode()了,我知道它会返回像Map
我有Product类和ItemCard类:
class ItemCard extends StatelessWidget{
final Product product;
final Function press;
const ItemCard({ Key key, this.product, this.press }) : super(key: key);
@override
Widget build(BuildContext context){
return GestureDetector(
onTap: press,
child: Column(
children: <Widget>[
Expanded(
child: Container(
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(16),
),
/*
child: Hero(
tag: "${product.id}",
child: Image.asset(product.image),
),
*/
),
),
Text(product.brand),
],
),
);
}
}
还有,我的清单:
Container(
child: Expanded(
child: FutureBuilder(
future: DefaultAssetBundle.of(context)
.loadString('assets/watches.json'),
builder: (context,snapshot){
//print(snapshot.data);
var jsondata = jsonDecode(snapshot.data.toString());
return GridView.builder(
itemCount: jsondata.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
childAspectRatio: 0.75
),
itemBuilder: (context, index) => ItemCard(
product: jsondata[index],
press: (){}
),
);
},
),
),
),
我该如何解决?任何想法都会有所帮助
答案 0 :(得分:0)
您需要将作为映射的jsondata[index]
转换为Product
实例。通常,您可以使用fromJson
方法从json映射中创建实例。
product: Product.fromJson(jsondata[index]),
这是toJson
和fromJson
实现的示例
class User {
final String name;
final String email;
User(this.name, this.email);
User.fromJson(Map<String, dynamic> json)
: name = json['name'],
email = json['email'];
Map<String, dynamic> toJson() =>
{
'name': name,
'email': email,
};
}