【发布时间】:2021-07-02 04:15:21
【问题描述】:
我正在使用具有标题和操作按钮的可重用 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 小部件是无状态的,不能是有状态的。
【问题讨论】:
-
请问您是否使用任何类型的提供商?
-
不使用提供者