有没有人可以帮助我使用英雄小部件将 JSON 数据解析到另一个页面



我希望有人帮助我将 JSON 数据解析到 HERO 小部件中的另一个页面。我将数据解析到第一页,但无法将数据解析到另一页

使JSON数据的模型使用PODO样式 像这样,它将处理所有要解析到视图类的 JSON 数据。

class ProductResponse{
  List<ProductDetail> results;
  ProductResponse({this.results});
  ProductResponse.fromJson(Map<String,dynamic> json){
    if(json['results'] !=null){
      results=new List<ProductDetail>();
      json['results'].forEach((v){
        results.add(new ProductDetail.fromJson(v));
      });
    }
  }
Map<String,dynamic> toJson(){
  final Map<String, dynamic> data = new Map<String, dynamic>();
  if (this.results != null) {
    data['results'] = this.results.map((v) => v.toJson()).toList();
  }
  return data;
}
}
class ProductDetail{
  int phone;
  int price;
  int qty;
  String amount;
  String place;
  String image_name;
  String image_url;
  String vendor_name;
  String description;
  String category;
  String productName;
  String images;
  ProductDetail({this.phone, this.price, this.qty, this.amount, this.vendor_name,
    this.description, this.category, this.productName, this.images,this.image_name,this.image_url,this.place});
   ProductDetail.fromJson(Map<String,dynamic> json){
        phone = json['phone'];
        price = json["price"];
        qty = json['qty'];
        amount =json['amount'];
        vendor_name =json['vendor_name'];
        description = json['description'];
        category = json['category'];
        images = json['images'];
        productName = json['productName'];
        image_url =json['image_url'];
        image_name =json['image_name'];
        place =json['place'];
  }
  Map<String,dynamic> toJson(){
     final Map<String,dynamic> data =new Map<String,dynamic>();
     data['phone'] =this.phone;
     data['price'] =this.price;
     data['qty'] =this.qty;
     data['amount'] =this.amount;
     data['vendor_name'] =this.vendor_name;
     data['description'] =this.description;
     data['category'] =this.category;
     data['productName'] =this.productName;
     data['images'] =this.images;
     data['place'] = this.place;
     data['image_url'] =this.image_url;
     data['image_name'] =this.image_name;
     return data;
  }
}

创建将向服务器发出请求的类

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:kilimo_biashara1/Model/Dialogs.dart';
import 'package:kilimo_biashara1/Model/ProductDetail.dart';
import 'package:kilimo_biashara1/Products/ProductPage.dart';
class Products extends StatefulWidget {
  @override
  _ProductsState createState() => _ProductsState();
}
class _ProductsState extends State<Products> {
  String url = "put your api url here";
  ProductResponse detail;// declare the class from PODO
  fetchProduct() async {
    var response = await http.get(url);
    var decodeJson = jsonDecode(response.body);
    print("response" + response.body);
    setState(() {
      detail = ProductResponse.fromJson(decodeJson);
    });
    print(detail);//debug
  }    
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        body: detail == null
            ? Center(
          child: CircularProgressIndicator(),
        )
          : StaggeredGridView.countBuilder(
          crossAxisCount: 4,
          itemCount: detail.results.length,
          itemBuilder: (BuildContext context, int index) {
            return ProductPage(
                detail: detail.results[index]
            ); //Return the product page
          },
          staggeredTileBuilder: (_) => StaggeredTile.fit(2),
          mainAxisSpacing: 4.0,
          crossAxisSpacing: 4.0,
        )
    );
  }
}

这是产品的示例代码 page.in 此产品页面将显示包含很少详细信息的卡片

import 'package:flutter/material.dart';
import 'package:kilimo_biashara1/Products/DetailProduct.dart';
import 'package:kilimo_biashara1/Model/ProductDetail.dart';
 class ProductPage extends StatelessWidget {
   final ProductDetail detail;
   ProductPage({@required this.detail});
   @override
   Widget build(BuildContext context) {
     return Card(
       shape: RoundedRectangleBorder(
         borderRadius: BorderRadius.circular(4.0),
       ),
       elevation: 4.0,
       margin: EdgeInsets.all(4.0),
       child: InkWell(
         radius: 4.0,
         child: getCardView(context),
         onTap: (){
           Navigator.push(
            context,
            MaterialPageRoute(builder: (context) =>
            DetailProduct(
              detail: detail,
            ),
            ),
           );
         },
       ),
     );
   }
   //////
   getCardView(BuildContext context){
     return Column(
       mainAxisSize: MainAxisSize.min,
       crossAxisAlignment: CrossAxisAlignment.start,
       children: <Widget>[
         Hero(
             tag: detail,//this key /tag will be the same with another page also
             child: Container(
               height: 200.0,
             decoration: BoxDecoration(
               borderRadius: BorderRadius.circular(8.0),
               image: DecorationImage(
                   image: NetworkImage("${detail.image_url}"
                      ,
                   ),
                   fit: BoxFit.cover),
             ),
             ), ),
      //   Image.asset("images/ndz.jpg"),
         Padding(
           padding: const EdgeInsets.all(4.0),
           child: Column(
             crossAxisAlignment: CrossAxisAlignment.start,
             children: <Widget>[
               Text("sold by: "+
                 detail.vendor_name,
                 overflow: TextOverflow.ellipsis,
                 style: Theme
                     .of(context)
                     .textTheme
                     .body2,
               ),
               Text("product: "+
                 detail.productName,
                 softWrap: true,
                 overflow: TextOverflow.ellipsis,
                 style: Theme
                     .of(context)
                     .textTheme
                     .body2,
               ),
               Text("price: ${detail.price} ${detail.amount}"
                ,
                 softWrap: true,
                 overflow: TextOverflow.ellipsis,
                 style: Theme
                     .of(context)
                     .textTheme
                     .body2,
               ),
             ],
           ),
         ),
       ],
     );
   }
 }

当它被点击/点击时,它将定向到另一个页面,该页面将提供有关产品的完整详细信息

import 'package:flutter/material.dart';
import 'package:kilimo_biashara1/Model/ProductDetail.dart';
import 'package:kilimo_biashara1/payment/Payment.dart';
class DetailProduct extends StatelessWidget {
  final ProductDetail detail;
  DetailProduct({this.detail});
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        persistentFooterButtons: <Widget>[
             Padding(
               padding: const EdgeInsets.fromLTRB(15.0, 5.0, 40.0, 5.0),
               child: new Text("SHOPPING",
                  style: new TextStyle(fontSize: 25.0,color: Colors.green,fontWeight: FontWeight.bold),
                ),
             ),
            new FlatButton(
            child: new Icon(Icons.shopping_cart,size: 35.0,),
            onPressed:(){
    Navigator.of(context).push(
    new MaterialPageRoute(
    builder: (BuildContext context)=>new Payment()));
    } ,
          ),
        ],
        body:new Scaffold(
    body:ListView(
    children: <Widget>[
      Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Hero(
              tag: detail,
              child: Container(
                height: 250.0,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(16.0),
                  shape: BoxShape.rectangle,
                  image: DecorationImage(
                    image: NetworkImage(
                      "${detail.image_url}",
                    ),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
           // Image.asset("images/ndz.jpg"),
            SizedBox(
              height: 16.0,
            ),
            Text("vendor name:  "+
              detail.vendor_name,
              style: Theme.of(context).textTheme.title,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("product name: "+
              detail.productName,
              style: Theme.of(context).textTheme.subhead,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("vendor place: "+
              detail.place,
              style: Theme.of(context).textTheme.subhead,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("price:  ${detail.price}  ${detail.amount}",
              style: Theme.of(context).textTheme.subhead,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("short description:  "+
              detail.description,
              style: Theme.of(context).textTheme.subhead,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("Category:  "+detail.category,
              style: Theme.of(context).textTheme.subhead,
            ),
            SizedBox(
              height: 16.0,
            ),
            Text("contacts:  ${detail.phone}",
              style: Theme.of(context).textTheme.subhead,
            ),
          ],
        ),
      ),
    ],
    ),
    ),
    ),
    );
  }
}

执行这些步骤后,您应该可以使用 hero 小部件从 API 解析数据

最新更新