简体   繁体   English

如何在 Flutter Z4E9F7F44562A881ZFE61E0DABFFE0AC02 中为 Json object 创建事件侦听器

[英]How do i create event listener for Json object in Flutter gridview

i would like to know how i can listen to json objects in my gridview so that i can use them for navigation logic.Forexample picking a category id of a gridview item and using it to display it's respective data or items in the next page.我想知道如何在我的 gridview 中收听 json 对象,以便我可以将它们用于导航逻辑。例如选择 gridview 项目的类别 ID 并使用它在相应的数据或项目中显示它'

You can fetch the list to be shown in GridView from the network.您可以从网络上获取要在 GridView 中显示的列表。

getTags() async {
 var res = await Client().getAsync("yourURL");
 var decodedJson = jsonDecode(res.body);

 setState(() {
      tagList = decodedJson;
    });
 }

Now you can use GridView.builder and InkWell to navigate to another screen.现在您可以使用 GridView.builder 和 InkWell 导航到另一个屏幕。

 GridView.builder(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    childAspectRatio: MediaQuery.of(context).size.width /
                        ((MediaQuery.of(context).size.height) / 2),
                  ),
                  itemCount: tagList.length,
                  itemBuilder: (BuildContext context, int index) {
                    Tag tag = (tagList)[index];

                    return InkWell(
                     onTap:(){
                      Navigator.push(
                       context,
                       MaterialPageRoute(builder: (context) => 
                         YourPageClass(yourId: tag.id)),
                       );
                     },
                     child: Container()


                   )
                  },
                ),

Here is the code for the Tag class.这是标签 class 的代码。

class Tag {
    int id;
    Tag({this.id,});

    Tag.fromJson(Map<String, dynamic> json) {
     id = json['id'];
    }

    Map<String, dynamic> toJson() {
      final Map<String, dynamic> data = new Map<String, dynamic>();
      data['id'] = this.id;

      return data;
    }
   }

Final Output:最终 Output:

在此处输入图像描述

Full working code:完整的工作代码:

import 'package:flutter/material.dart';

/* This is the data that we are going to use to render the grid of products using Gridview.
As pointed out by Pranay, you can use the fetched data from a remote server. 
but for the sake of simplicity, I am using hardcoded data. 
*/

List data = [
  {
    "id": 1,
    "name": "Mix Pina Colada 1",
    "desc": "Ice Cream Bar - Oreo Cone 1",
    "image": "http://dummyimage.com/110x138.png/dddddd/000000",
    "price": 93,
    "quantity": 0,
  },
  {
    "id": 2,
    "name": "Cake - Bande Of Fruit",
    "desc": "Cheese - Cheddar With Claret",
    "image": "http://dummyimage.com/172x223.png/cc0000/ffffff",
    "price": 4,
    "quantity": 0,
  },
  {
    "id": 3,
    "name": "Lid Coffee Cup 8oz Blk",
    "desc": "Rosemary - Primerba, Paste",
    "image": "http://dummyimage.com/110x243.png/ff4444/ffffff",
    "price": 18,
    "quantity": 0,
  },
];

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'GridView Example'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  List products = data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.amber,
      appBar: AppBar(
        title: Text(title),
      ),
      body: GridView.count(
        primary: false,
        padding: const EdgeInsets.all(20),
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        crossAxisCount: 2,
        children: products.map((product) {
          print(product["name"]);
          return InkWell(
            onTap: () {
             /* Using Navigator we will navigate to DetailsScreen, 
             along with it we will also pass the product object which 
             will be used to render the product details of the clicked item 
             */
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => DetailsScreen(
                    product: product,
                  ),
                ),
              );
            },
            child: Container(
                color: Colors.white,
                padding: EdgeInsets.all(10),
                child: Text(product["name"])),
          );
        }).toList(),
      ),
    );
  }
}

/*
The following widget tasked the product object that we passed in 
Navigator, and displays the data of that particular product.
*/

class DetailsScreen extends StatelessWidget {
  final dynamic product;
  DetailsScreen({this.product});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(product["name"])),
      body: Column(
        children: [
          Image.network(
            product["image"],
            width: double.infinity,
            height: 200,
            color: Colors.amberAccent,
          ),
          Text("Name: " + product["name"]),
          Text("Description: " + product["desc"]),
          Text("Price: " + product["price"].toString()),
        ],
      ),
    );
  }
}

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

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