简体   繁体   中英

How to return json data from local storage in flutter app

I have json file and i want to display it in Container. I have tried many things but nothing works. For now, I have this error I have tried with jsonDecode(), i know it returns a map like this Map<String, dynamic>, but i don't know how to fix this

I have Product class and 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),
        ],
      ),
    );
  }
}

And in body, my List:

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

How can I fix this? any idea would help

You need to convert jsondata[index] that is a map into a Product instance. Normally you would have a fromJson method to create the instance from a json map.

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

This is an example of toJson and fromJson implementation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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