Flutter异常 NoSuchMethodError The getter focusScopeNode was called on null

在启动新页面是出现异常:

 [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The 
getter 'focusScopeNode' was called on null.
E/flutter (26425): Receiver: null    
E/flutter (26425): Tried calling: focusScopeNode
E/flutter (26425): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter (26425): #1      Route.didPush.<anonymous closure> (package:flutter/src/widgets/navigator.dart:139:17)  

错误代码:

 void _onPass(){
    Navigator.push(context, MaterialPageRoute(builder: (context){
      return DetailPage();
    }));
    Navigator.pop(context);
  }

出现异常的原因是在刚push界面之后,不能立即调用Navigator.pop(context),

Navigator.pop方法看源码声明:


  /// Pop the top-most route off the navigator.
  ///
  /// {@macro flutter.widgets.navigator.pop}
  ///
  /// {@tool sample}
  ///
  /// Typical usage for closing a route is as follows:
  ///
  /// ```dart
  /// void _handleClose() {
  ///   navigator.pop();
  /// }
  /// ```
  /// {@end-tool}
  /// {@tool sample}
  ///
  /// A dialog box might be closed with a result:
  ///
  /// ```dart
  /// void _handleAccept() {
  ///   navigator.pop(true); // dialog returns true
  /// }
  /// ```
  /// {@end-tool}
  @optionalTypeArgs
  bool pop<T extends Object>([ T result ]) {
    assert(!_debugLocked);
    assert(() {
      _debugLocked = true;
      return true;
    }());

可以将页面路由当做一个栈,在刚push进去一个页面时,

立即调用Navigator.pop(context)会将栈顶的页面删除,此时push的页面就不能正常启动,会报上述异常

看源码,官方给的推荐用法:

/// The state from the closest instance of this class that encloses the given context.
  ///
  /// Typical usage is as follows:
  ///
  /// ```dart
  /// Navigator.of(context)
  ///   ..pop()
  ///   ..pop()
  ///   ..pushNamed('/settings');
  /// ```
  ///
  /// If `rootNavigator` is set to true, the state from the furthest instance of
  /// this class is given instead. Useful for pushing contents above all subsequent
  /// instances of [Navigator].

修改之后代码:

void _onPass(){
    Navigator.of(context)
      ..pop()
      ..push(MaterialPageRoute(builder: (context){
        return DetailPage();
      }));
  }

或者

 void _onPass(){
    Navigator.pop(context);
    Navigator.push(context, MaterialPageRoute(builder: (context){
      return DetailPage();
    }));
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值