NoSuchMethodError:方法“ ancestorStateOfType”在null上调用

时间:2018-09-01 17:35:29

标签: dart flutter dart-2

我正在像这样的流媒体列表一样进行屏幕切换,当它发出时,我会切换屏幕

 @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)

2 个答案:

答案 0 :(得分:5)

您的窗口小部件很可能已从树中删除。因此,它不再具有context

问题是,您忘记了退订Stream。因此,即使将其从树中删除后,您的小部件仍会尝试更新。

一种解决方案是在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();
  }
}

答案 1 :(得分:2)

问题:这是传递给子窗口小部件的错误上下文。

解决方案:在传递了Build方法上下文(这是传递给子窗口小部件的正确上下文)之后,我的问题已解决。