让ChangeNotificationer类依赖于Stream的正确方法是什么



我有一个名为MyChangeNotifier的类。每当AppNotification类发布到流时,该类都需要运行一个行为。我已经完成了这项工作,但我不确定这是否是使用提供者库完成这项工作的正确方法。

我使用StreamProvider提供AppNotification流如下。。。

MultiProvider(
providers: [
...,
StreamProvider<AppNotification?>.value(value: _notificationService.notificationsStream, initialData: null),
],
child: ...
),

然后,在小部件树下,我有一个StatlessWidget,它的工作是专门使用流中的AppNotification事件,并将它们传递给MyChangeNotificationer类。。

class AppNotificationConsumer extends StatelessWidget {
final Widget child;
const AppNotificationConsumer(this.child , {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Consumer<AppNotification?>(
builder: (context , notification , widget) {
if (notification != null) {
var model = Provider.of<MyChangeNotifer>(context , listen: false);
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
model.handleNotification(notification);
});
}
}
return child;
},
);
}
}

在这里,我将这个逻辑连接到StatelessWidget的构建方法中。我必须使用addPostFrameCallback,因为handleNotification调用调用overlay_support库showNotification(),它遍历小部件树(在构建中无法调用(。

有没有一种使用提供者的方法,我可以在不使用StatelessWidget的情况下绑定MyChangeNotifierAppNotification流。。。。还是这是正确的方法?

有一种更简单的方法。只需使用ChangeNotifierProxyProvider

它会是这样的:

MultiProvider(
providers: [
...,
StreamProvider<AppNotification?>.value(value: _notificationService.notificationsStream, initialData: null),
// Here   ---v
ChangeNotifierProxyProvider<AppNotification?, MyChangeNotifer>(
create: (_) => MyChangeNotifer(),
update: (_, notification, myChangeNotifier) =>
myChangeNotifier!..handleNotification(notification),
),
],
child: ...
),

每次出现新的AppNotification时,都会调用更新,以便有机会更新其他内容。还有ChangeNotifierProxyProvider2ChangeNotifierProxyProvider3(等等(,它们分别具有2个或3个其他依赖项,而不是只有1个。

相关内容

最新更新