NoSuchMethodError: The method 'ancestorStateOfType' was called on null

ε祈祈猫儿з 提交于 2020-02-28 07:10:12

问题


i am doing screen change like this iam listing for stream and when it emit i change the screen

 @override
 void initState() {
    super.initState();

     appBloc.error.listen((data) {
     _scaffoldKey.currentState.showSnackBar(new SnackBar(content: new 
        Text(data)));
    });

     appBloc.success.listen((_) => goToDashBoardScreen(context));

}

and doToDashBoardScreen look like this

Navigator.pushReplacement(context, new SlideRightRoute(widget: 
DashBoardScreen()));

but i am getting error like this but i change the page.

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)

回答1:


Your widget has most likely been removed from the tree. Therefore it doesn't have a context anymore.

The problem being, you forgot to unsubscribe to your Stream. Therefore even after being removed from the tree, your widget still attempts to update.

A solution would be to unsubscribe on dispose call:

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();
  }
}



回答2:


Problem : It was the wrong context passed to a child widget.

Solution : After passing the Build method context which was the correct context to pass to the child widget my issue was resolved.



来源:https://stackoverflow.com/questions/52130648/nosuchmethoderror-the-method-ancestorstateoftype-was-called-on-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!