RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1602195
Accepted
Linar Chingizov
Linar Chingizov
Asked:2024-12-11 17:27:58 +0000 UTC2024-12-11 17:27:58 +0000 UTC 2024-12-11 17:27:58 +0000 UTC

购买 Flutter Provider 产品

  • 772

请帮我实现这个方法,我是 Flutter 的新手。

如何使用 Provider 来实现

(不仅 Provider 是可能的,对我来说最主要的是了解如何在实践中实现和应用)

当您单击“购买”按钮时(在本例中我只有一个),从列表中传输数据,仅“Orange”*(如果“Mandarin”-则数据“Mandarin”)*

同时,如果您单击“下订单”按钮,则会删除第一个屏幕中的数据。

在此输入图像描述

List <String> Name = ['Апельсин', 'Мандарин', 'Помидор'];
List <int> Price = [70,60,80];


class MainApp extends StatelessWidget {
const MainApp({super.key});

@override
Widget build(BuildContext context) {
return const MaterialApp(
  debugShowCheckedModeBanner: false,
  home: MyHomePage(),
   );
  }
 }

 class MyHomePage extends StatelessWidget {
 const MyHomePage({super.key});


 @override
 Widget build(BuildContext context) {
 return Scaffold(
  appBar: AppBar(
    title: const Text('Main'),
  ),
  body: ListView.builder(
    itemCount: Name.length,
    itemBuilder: (BuildContext context, int index) {
      return Card(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.only(left: 10, top: 50, bottom: 50),
              child: Text(Name[index].toString()),
            ),
            Row(children: [
              Padding(
              padding: EdgeInsets.only(left: 100, top: 50, bottom: 50),
              child: Text(Price[index].toString()),
                              ),
            Padding(
              padding: const EdgeInsets.only(left: 100),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextButton(onPressed: (){Navigator.push(context,
          CupertinoPageRoute(builder: (context) => const SalePage()));}, child: const 
            Text('Купить')),
                              ],
                             ),
                            )
                          ]),
                         ],
                        ),
                       );
                      },
                     ),
                    );
                   }
                  }
sql
  • 1 1 个回答
  • 24 Views

1 个回答

  • Voted
  1. Best Answer
    MiT
    2024-12-12T03:21:35Z2024-12-12T03:21:35Z

    以下是您的错误以及为什么它不适合您:

    1. 使用两个列表(Name和Price)而不是结构。
    2. 没有共享存储。
    3. 人们不知道篮子应该如何工作,数据应该如何进入篮子。

    下面是一个实际示例及其分析:

    import 'package:flutter/material.dart';
    import 'package:flutter/cupertino.dart';
    import 'package:provider/provider.dart';
    
    void main() {
      runApp(const MainApp());
    }
    
    class Product {
      const Product(this.name, this.price);
    
      final String name;
      final int price;
    }
    
    class Store with ChangeNotifier {
      Set<Product> _products = <Product>{
        Product('Апельсин', 70),
        Product('Мандарин', 60),
        Product('Помидор', 80),
      };
    
      List<Product> get products => _products.toList();
    
      Product? _cart = null;
    
      Product? get cart => _cart;
    
      void addToCart(Product product) {
        _cart = product;
    
        notifyListeners();
      }
    
      void removeFromCart(Product product) {
        _cart = null;
    
        notifyListeners();
      }
    
      void buy() {
        _products.remove(_cart);
    
        _cart = null;
    
        notifyListeners();
      }
    }
    
    class MainApp extends StatelessWidget {
      const MainApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (_) => Store()),
          ],
          child: MaterialApp(
            debugShowCheckedModeBanner: false,
            home: MyHomePage(),
          ),
        );
      }
    }
    
    class MyHomePage extends StatelessWidget {
      const MyHomePage({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Main'),
          ),
          body: ListView.builder(
            itemCount: context.watch<Store>().products.length,
            itemBuilder: (BuildContext context, int index) {
              final product = context.watch<Store>().products[index];
    
              return Card(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 10, top: 50, bottom: 50),
                      child: Text(product.name.toString()),
                    ),
                    Row(
                      children: [
                        Padding(
                          padding: EdgeInsets.only(left: 100, top: 50, bottom: 50),
                          child: Text(product.price.toString()),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(left: 100),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              TextButton(
                                  onPressed: () async {
                                    context.read<Store>().addToCart(product);
    
                                    await Navigator.push(
                                      context,
                                      CupertinoPageRoute(
                                        builder: (context) => const SalePage(),
                                      ),
                                    );
                                    
                                    context.read<Store>().removeFromCart(product);
                                  },
                                  child: const Text('Купить')),
                            ],
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              );
            },
          ),
        );
      }
    }
    
    class SalePage extends StatelessWidget {
      const SalePage({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('SalePage'),
          ),
          floatingActionButton: FloatingActionButton(
            key: const Key('floatingActionButton'),
            onPressed: () => context.read<Store>().buy(),
            tooltip: 'Buy',
            child: const Icon(Icons.add),
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
          body: ListView.builder(
            itemCount: context.watch<Store>().cart != null ? 1 : 0,
            itemBuilder: (BuildContext context, int index) {
              return Card(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 10, top: 50, bottom: 50),
                      child: Text(context.watch<Store>().cart!.name.toString()),
                    ),
                    Row(
                      children: [
                        Padding(
                          padding: EdgeInsets.only(left: 100, top: 50, bottom: 50),
                          child:
                              Text(context.watch<Store>().cart!.price.toString()),
                        )
                      ],
                    ),
                  ],
                ),
              );
            },
          ),
        );
      }
    }
    

    类Product代表了产品的本质。它有两个属性:

    • name——产品名称。
    • price- 价格。

    类Store是应用程序的主要状态存储。它是使用 mixin 实现的ChangeNotifier,它允许小部件收到状态更改的通知。

    主要性能Store:

    • _products:有很多产品可供购买。
    • _cart:添加到“购物车”进行购买的所选产品。

    方法Store:

    • products:返回产品列表的 getter。
    • cart:返回购物车中当前产品的 getter。
    • addToCart(Product product):将产品添加到购物车。
    • removeFromCart(Product product): 清空垃圾箱。
    • buy():从可用产品列表中删除产品,清空购物车。

    它是如何运作的notifyListeners()?

    该方法notifyListeners()通知所有订阅的小部件(通过Provider)存储状态已更改。这允许您使用更新的数据自动重建界面。

    转帐Store方式Provider:

    Store要从应用程序中的任何位置访问,请使用provider.

    环境Provider:

    在应用程序的根部(在 MainApp 中),Store 通过 ChangeNotifierProvider 传递:

    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => Store()),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: MyHomePage(),
      ),
    )
    

    现在任何子小部件都可以使用以下方式访问商店:

    • context.watch<Store>():读取状态并在更改时自动重建。
    • context.read<Store>():读取状态而不订阅更改。

    顺便说一句,代码几乎已经准备好与购物车中的许多产品一起使用,因为这就是我最初完成此任务的方式。如果你想练习的话,就自己尝试一下吧!

    • 0

相关问题

  • 通过 OUT 参数从过程结果输出

  • ON 关键字附近的语法错误 - SQL

  • 多表查询中的 Count() 聚合函数

  • 根据时间更改单元格中的日期

  • phpMyAdmin 中的错误 #1064 SQL 查询

  • Qt:包含变量的数据库查询

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5