我正在像这样的流媒体列表进行屏幕更改,当它发出时,我更改屏幕
@override void initState() { super.initState(); appBloc.error.listen((data) { _scaffoldKey.currentState.showSnackBar(new SnackBar(content: new Text(data))); }); appBloc.success.listen((_) => goToDashBoardScreen(context)); }
和doToDashBoardScreen看起来像这样
Navigator.pushReplacement(context, new SlideRightRoute(widget: DashBoardScreen()));
但是我遇到这样的错误,但是我更改了页面。
22:05:02.446 3 info flutter.tools E/flutter (13216): NoSuchMethodError: The method 'ancestorStateOfType' was called on null. 22:05:02.446 4 info flutter.tools E/flutter (13216): Receiver: null 22:05:02.446 5 info flutter.tools E/flutter (13216): Tried calling: ancestorStateOfType(Instance of 'TypeMatcher<NavigatorState>') 22:05:02.446 6 info flutter.tools E/flutter (13216): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:48:5) 22:05:02.446 7 info flutter.tools E/flutter (13216): #1 Navigator.of (package:flutter/src/widgets/navigator.dart:1270:19) 22:05:02.446 8 info flutter.tools E/flutter (13216): #2 Navigator.pushReplacement (package:flutter/src/widgets/navigator.dart:952:22)
您的窗口小部件很可能已从树中删除。因此,它不再具有context。
context
问题是,您忘记了退订Stream。因此,即使将其从树中删除后,您的小部件仍会尝试更新。
Stream
一种解决方案是在dispose通话时退订:
dispose
class Foo extends StatefulWidget { @override _FooState createState() => _FooState(); } class _FooState extends State<Foo> { StreamSubscription streamSubscription; @override void initState() { super.initState(); streamSubscription = Bloc.of(context).myStream.listen((value) { print(value); }); } @override void dispose() { streamSubscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Container(); } }