如何在Flutter应用中从本地存储返回JSON数据

时间:2020-08-02 20:07:45

标签: json flutter local-storage

我有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: (){}
                    ),
                  );
              },
            ),
          ),
        ),

我该如何解决?任何想法都会有所帮助

1 个答案:

答案 0 :(得分:0)

您需要将作为映射的jsondata[index]转换为Product实例。通常,您可以使用fromJson方法从json映射中创建实例。

product: Product.fromJson(jsondata[index]),

这是toJsonfromJson实现的示例

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,
    };
}