【问题标题】:How to Pass Data from child widgets to parents widgets in dart?如何将数据从子小部件传递到飞镖中的父小部件?
【发布时间】:2021-04-23 17:55:38
【问题描述】:

我正在学习 dart/flutter,并且我有一个演示电子商务项目。我使用需要发送到父小部件的 POST API 在子小部件中加载了产品图片、标题和价格数据。有什么帮助吗? 如下所示,我与代码共享 dart 文件,并希望在购物车中显示点击项目而不继续或导航。 这是主页。

import 'dart:convert';
import 'package:ecom_demo/Screens/Details.dart';
import 'package:ecom_demo/Screens/MyCart.dart';
import 'package:flutter/material.dart';
import 'package:ecom_demo/Models/CartModel.dart';
import 'package:http/http.dart' as http;

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {      

  final cartr = CartResponse();
   

 

  Future<CartResponse> getData() async {
    final response = await http.post(
        'http://205.134.254.135/~mobile/MtProject/api/v1/product_list',
        headers: {
          'token':
              'eyJhdWQiOiI1IiwianRpIjoiMDg4MmFiYjlmNGU1MjIyY2MyNjc4Y2FiYTQwOGY2MjU4Yzk5YTllN2ZkYzI0NWQ4NDMxMTQ4ZWMz',
        },
        body: jsonEncode({"page": 1, "perPage": 5}));

    if (response.statusCode == 200) {
      return CartResponse.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('error');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Stack(children: [
            Text(''),
          ]),
          InkWell(
              onTap: () {
                Navigator.push(
                    context, MaterialPageRoute(builder: (context) => MyCart()));
              },
              child: Icon(Icons.shopping_cart))
        ],
        title: Text('HomePage'),
        centerTitle: true,
      ),
      body: FutureBuilder<CartResponse>(
        future: getData(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              shrinkWrap: true,
              itemCount: snapshot.data.data.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  height: MediaQuery.of(context).size.height * 0.7,
                  child: Column(
                    children: [
                      Expanded(
                          child: GestureDetector(
                        onTap: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => Details(
                                        value: snapshot.data.data[index],
                                      )));
                        },
                        child: Image.network(
                          snapshot.data.data[index].featuredImage,
                          fit: BoxFit.cover,
                        ),
                      )),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          ListTile(
                            leading: Text(
                              'Price:',
                              style: TextStyle(
                                  fontSize: 20, fontWeight: FontWeight.bold),
                            ),
                            title: Text(
                                snapshot.data.data[index].price.toString()),
                          ),
                          ListTile(
                            leading: Text(
                              'Title:',
                              style: TextStyle(
                                  fontSize: 20, fontWeight: FontWeight.bold),
                            ),
                            title: Text(snapshot.data.data[index].title),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              OutlineButton(
                                onPressed: () {
                                 
                                },
                                child: Icon(Icons.delete),
                              ),
                              OutlineButton(
                                onPressed: () {
                               
                                },
                              ),
                            ],
                          ),
                        ],
                      )
                    ],
                  ),
                );
              },
            );
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}


here is my cart...            

    import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class MyCart extends StatelessWidget {

 

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('MyCart'),
        centerTitle: true,
      ),
      body: ListView.builder(
          itemCount: 2,
          itemBuilder: (BuildContext context, int index) {
            return Padding(
              padding: const EdgeInsets.all(12.0),
              child: Container(
                padding: EdgeInsets.all(5),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(18),
                    color: Colors.grey.withOpacity(0.2)),
                height: 150,
                width: MediaQuery.of(context).size.width,
                child: Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Container(
                        color: Colors.red,
                      ),
                    ),
                    Expanded(
                      flex: 2,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Text(''),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              Text('price:'),
                              Text('price'),
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              Text('Quantity:'),
                              Text(""),
                            ],
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
            );
          }),
      bottomSheet: Container(
        height: MediaQuery.of(context).size.height * 0.1,
        width: MediaQuery.of(context).size.width,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.only(
                topRight: Radius.circular(25), topLeft: Radius.circular(25)),
            color: Colors.grey),
        child: Row(
          children: [
            Text(''),
          ],
        ),
      ),
    );
  }
}

cart model classs...

    
import 'dart:convert';

CartResponse cartResponseFromJson(String str) =>
    CartResponse.fromJson(json.decode(str));

String cartResponseToJson(CartResponse data) => json.encode(data.toJson());

class CartResponse {
  CartResponse({
    this.status,
    this.message,
    this.totalRecord,
    this.perPage,
    this.totalPage,
    this.data,
  });

  int status;
  String message;
  int totalRecord;
  int perPage;
  int totalPage;
  List<Datum> data;

  factory CartResponse.fromJson(Map<String, dynamic> json) => CartResponse(
    status: json["status"],
    message: json["message"],
    totalRecord: json["totalRecord"],
    perPage: json["perPage"],
    totalPage: json["totalPage"],
    data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "status": status,
    "message": message,
    "totalRecord": totalRecord,
    "perPage": perPage,
    "totalPage": totalPage,
    "data": List<dynamic>.from(data.map((x) => x.toJson())),
  };
}

class Datum {
  Datum({
    this.id,
    this.slug,
    this.title,
    this.description,
    this.price,
    this.featuredImage,
    this.status,
    this.createdAt,
  });

  int id;
  String slug;
  String title;
  String description;
  int price;
  String featuredImage;
  String status;
  DateTime createdAt;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
    id: json["id"],
    slug: json["slug"],
    title: json["title"],
    description: json["description"],
    price: json["price"],
    featuredImage: json["featured_image"],
    status: json["status"],
    createdAt: DateTime.parse(json["created_at"]),
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "slug": slug,
    "title": title,
    "description": description,
    "price": price,
    "featured_image": featuredImage,
    "status": status,
    "created_at": createdAt.toIso8601String(),
  };
}


main.dart



        import 'package:ecom_demo/Screens/HomePage.dart';
    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {



    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            primarySwatch: Colors.deepOrange,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: HomePage(),
        );
      }
    }

  

【问题讨论】:

  • 请查看以下内容,以改进您的答案:stackoverflow.com/help/how-to-ask
  • 分享您的一些代码,以便我们提供帮助
  • 嘿@pedropimont。我想使用正确的详细信息将数据从产品页面发送到购物车应用程序。
  • 分享一下,你到目前为止做了什么

标签: flutter dart


【解决方案1】:

不确定我是否正确地回答了您的问题,但如果您想将任何类型的值从孩子传递给父母,那么您可以执行以下操作:

假设您需要小部件 Page1 [parent] 和 Page2 [child] 并且您想将字符串“hello world”从 Page2 传递到 Page1。

1) 在 Page2 小部件中:

当您使用 Navigator.pop 退出 Page2 时,您可以通过以下方式将值作为参数传递:

Navgiator.pop(context,"hello world");

2) 在 Page1 小部件中:

当您使用 Navigator.push 将 Page2 压入堆栈时,您可能已经知道,这是一个异步方法,它一直等到 Page2 弹出。 所以去你使用 Navigator.push() 的地方并添加一个 .then 方法。所以最终产品会是这样的:

Navigator.push(
      context,
      MaterialPageRoute(
            builder: (context) => Details(value: snapshot.data.data[index],)
     )
).then(result){
   print("Result received from Page2 : $result");
};

这个打印语句将打印我们的结果字符串“hello world”。

【讨论】:

    【解决方案2】:

    状态管理解决方案很简单,例如 InheritedWidget 或 Provider 或 Riverpod。请在 https://flutter.dev/docs/development/data-and-backend/state-mgmt/options 上查看 Google 对此的看法。

    【讨论】:

    • BLoC 模式非常适合大型复杂项目。在此之下,它似乎涉及许多其他机制不需要的样板。谷歌曾经相当强烈地推荐 BLoC,因为他们的 AdSense 和 AdWords 移动应用程序正在使用它,但开始支持 Provider 作为大多数小型项目的更好策略。我建议 Riverpod 在最小样板和使用灵活性方面都超过了 Provider。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2021-02-07
    相关资源
    最近更新 更多