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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章