flutter - 从多个小部件更新 AppBar 中的购物车徽章计数器
问题描述
我正在使用具有标题和操作按钮的可重用 AppBar 小部件。
在应用栏操作中,有收藏夹图标按钮和购物车图标按钮,带有一个显示购物车总项目的徽章:
应用栏小部件:
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
final BuildContext context;
final String title;
final bool showBackButton;
final Widget widget;
final bool showActions;
CustomAppBar({
@required this.context,
@required this.title,
this.showBackButton = true,
this.widget,
this.showActions = true,
});
@override
Widget build(BuildContext context) {
return AppBar(
title: Text(title),
leading: showBackButton
? new IconButton(
icon: new Icon(
Icons.arrow_back,
),
onPressed: () {
if (widget != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => widget,
),
);
return true;
} else {
Navigator.pop(context);
}
},
)
: null,
actions: !showActions ? null : <Widget>[
IconButton(
icon: const Icon(Icons.favorite_border),
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) {
return MainHome(
selectedIndex: 1,
);
},
),
);
},
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 5),
child: Badge(
position: BadgePosition.topEnd(top: 3, end: 3),
animationDuration: Duration(milliseconds: 300),
animationType: BadgeAnimationType.slide,
badgeColor: Colors.white,
toAnimate: true,
badgeContent: Text(
'5',
style: TextStyle(
fontSize: 8,
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.bold),
),
child: IconButton(
icon: const Icon(Icons.shopping_cart_rounded),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) {
return MainHome(
selectedIndex: 2,
);
},
),
);
},
),
),
),
],
);
}
@override
Size get preferredSize {
return new Size.fromHeight(kToolbarHeight);
}
}
每当用户添加到购物车、更新购物车、从购物车中删除时,我都想更新应用栏中的计数器。这可能发生在多个页面:产品列表页面、产品详细信息页面、购物车页面、搜索建议小部件。所有这些页面都有购物车操作(添加/更新/删除)。
我不想在每个页面中管理这个计数器。我需要一种在一个地方进行管理的方法,并在购物车更新时收到通知以更新徽章
我搜索了很多。有些人使用 GLobalKey 来管理状态,但在我的情况下不起作用,因为 appbar 小部件是无状态的,不能是有状态的。
解决方案
我建议您使用任何类型的提供程序,例如provider
包装,或者riverpod
,您需要一个叫做的东西notifyListeners
,每次您将新商品添加到购物车时通知购物车徽章,否则您的购物车商品将不会更新,除非在小部件上重建;比如导航之类的。
您可以从 pub.dev 查看 riverpod 和 provider,确保完全理解文档,因为它可能很棘手!
希望这个答案对你有帮助!
推荐阅读
- reactjs - 将 react-p5 npm 包的 p5js 加载到 NextJS 应用程序显示“ReferenceError:未定义窗口”
- url - 允许 IIS 上的特定 HTTP 引用器用于虚拟目录
- c++ - 如何在 Linux 上重现 Windows winusb 驱动程序的功能?我什至需要吗?
- amazon-web-services - AWS SAM 以及每次部署的资源 ARN 更改
- php - 无法从 laravel 中的主表中获取数据
- laminas - Laminas CollectionInputFilter - 验证最小/最大项目数
- java - 如何将控制台显示中的输出保存到 Java 中的文本文件中?
- java - Servlet 因 IOException 失败 weblogic.utils.NestedRuntimeException:无法解析请求的 POST 参数
- python - 动态地将参数传递给 objects.filter
- spring - 由于@JoinColumn(nullable = false),Spring/JPA 两次单向不起作用