ios – 当BLOC中的流值更改时导航到新屏幕

ios – 当BLOC中的流值更改时导航到新屏幕,第1张

概述在Flutter中,当流的值发生变化时,如何调用Navigator.push?我已经尝试了下面的代码,但得到了一个错误. StreamBuilder( stream: bloc.streamValue, builder: (BuildContext context, AsyncSnapshot<int> snapshot) { if (snaps 在Flutter中,当流的值发生变化时,如何调用Navigator.push?我已经尝试了下面的代码,但得到了一个错误.

StreamBuilder(        stream: bloc.streamValue,builder: (BuildContext context,AsyncSnapshot<int> snapshot) {          if (snapshot.hasData && snapshot.data == 1) {            Navigator.push(              context,MaterialPageRoute(builder: (context) => SomeNewScreen()),);          }          return Text("");        });

解决方法 您不应该使用StreamBuilder来处理导航.
StreamBuilder用于构建屏幕内容而不是其他内容.

相反,您将必须侦听流以手动触发副作用.这是通过使用StatefulWidget并重写initState / dispose来完成的:

class Example extends StatefulWidget {  final Stream<int> stream;  const Example({Key key,this.stream}) : super(key: key);  @overrIDe  ExampleState createState() => ExampleState();}class ExampleState extends State<Example> {  StreamSubscription _streamSubscription;  @overrIDe  voID initState() {    super.initState();    _Listen();  }  @overrIDe  voID dIDUpdateWidget(Example oldWidget) {    super.dIDUpdateWidget(oldWidget);    if (oldWidget.stream != Widget.stream) {      _streamSubscription.cancel();      _Listen();    }  }  voID _Listen() {    _streamSubscription = Widget.stream.Listen((value) {      Navigator.pushnamed(context,'/someRoute/$value');    });  }  @overrIDe  voID dispose() {    _streamSubscription.cancel();    super.dispose();  }  @overrIDe  Widget build(BuildContext context) {    return Container();  }}

请注意,如果您使用inheritedWidget来获取流(通常是BLoC),则需要使用dIDChangeDependencIEs而不是initState / dIDUpdateWidget.

这导致:

class Example extends StatefulWidget {  @overrIDe  ExampleState createState() => ExampleState();}class ExampleState extends State<Example> {  StreamSubscription _streamSubscription;  Stream _prevIoUsstream;  voID _Listen(Stream<int> stream) {    _streamSubscription = stream.Listen((value) {      Navigator.pushnamed(context,'/someRoute/$value');    });  }  @overrIDe  voID dIDChangeDependencIEs() {    super.dIDChangeDependencIEs();    final bloc = MyBloc.of(context);    if (bloc.stream != _prevIoUsstream) {      _streamSubscription?.cancel();      _prevIoUsstream = bloc.stream;      _Listen(bloc.stream);    }  }  @overrIDe  voID dispose() {    _streamSubscription.cancel();    super.dispose();  }  @overrIDe  Widget build(BuildContext context) {    return Container();  }}
总结

以上是内存溢出为你收集整理的ios – 当BLOC中的流值更改时导航到新屏幕全部内容,希望文章能够帮你解决ios – 当BLOC中的流值更改时导航到新屏幕所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1001851.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存