繁体   English   中英

flutter app中如何从本地存储返回json数据

[英]How to return json data from local storage in flutter app

我有 json 文件,我想在容器中显示它。 我尝试了很多东西,但没有任何效果。 现在,我遇到了这个错误,我已经尝试使用 jsonDecode(),我知道它返回一个 map,就像这个 Map<String, dynamic>,但我不知道如何解决这个问题

我有产品 class 和 ItemCard class:

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

我怎样才能解决这个问题? 任何想法都会有所帮助

您需要将 map 的jsondata[index]转换为Product实例。 通常,您会使用fromJson方法从 json map 创建实例。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM