Flutter:小部件和导航的生命周期

hen*_*dra 7 lifecycle widget viewdidappear onpause flutter

我写了一个flutter插件,可以显示相机预览并扫描条形码。我有一个Widget呼叫ScanPage,它显示,CameraPreviewRoute在检测到条形码时导航到新的。

问题: 当我将新的路线(SearchProductPage)推入导航堆栈时,CameraController继续检测条形码。从屏幕上删除时,我需要致电stop()我。当用户返回时,我需要再次致电。CameraControllerScanPagestart()ScanPage

我尝试过的东西:CameraController工具WidgetsBindingObserver并 对此做出反应didChangeAppLifecycleState()。当我按下主屏幕按钮时,此方法非常有效,但当我将新按钮推入Route导航堆栈时,此方法则无效。

问: 是否有一个等效viewDidAppear()viewWillDisappear()iOS上或onPause()onResume()Android上的Widgets在颤振?如果不是,我如何启动和停止我的浏览器,CameraController以便在导航堆栈顶部有另一个Widget时停止扫描条形码?

class ScanPage extends StatefulWidget {

  ScanPage({ Key key} ) : super(key: key);

  @override
  _ScanPageState createState() => new _ScanPageState();

}

class _ScanPageState extends State<ScanPage> {

  //implements WidgetsBindingObserver
  CameraController controller;

  @override
  void initState() {

    controller = new CameraController(this.didDetectBarcode);
    WidgetsBinding.instance.addObserver(controller);

    controller.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    });
  }

  //navigate to new page
  void didDetectBarcode(String barcode) {
      Navigator.of(context).push(
          new MaterialPageRoute(
            builder: (BuildContext buildContext) {
              return new SearchProductPage(barcode);
            },
          )
      );    
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(controller);
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    if (!controller.value.initialized) {
      return new Center(
        child: new Text("Lade Barcodescanner..."),
      );
    }

    return new CameraPreview(controller);
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

/// Controls a device camera.
///
///
/// Before using a [CameraController] a call to [initialize] must complete.
///
/// To show the camera preview on the screen use a [CameraPreview] widget.
class CameraController extends ValueNotifier<CameraValue> with WidgetsBindingObserver {

  int _textureId;
  bool _disposed = false;

  Completer<Null> _creatingCompleter;
  BarcodeHandler handler;

  CameraController(this.handler) : super(const CameraValue.uninitialized());

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {

    switch(state){
      case AppLifecycleState.inactive:
        print("--inactive--");
        break;
      case AppLifecycleState.paused:
        print("--paused--");
        stop();
        break;
      case AppLifecycleState.resumed:
        print("--resumed--");
        start();
        break;
      case AppLifecycleState.suspending:
        print("--suspending--");
        dispose();
        break;
    }
  }

  /// Initializes the camera on the device.
  Future<Null> initialize() async {

    if (_disposed) {
      return;
    }
    try {
      _creatingCompleter = new Completer<Null>();
      _textureId = await BarcodeScanner.initCamera();

      print("TextureId: $_textureId");

      value = value.copyWith(
        initialized: true,
      );
      _applyStartStop();
    } on PlatformException catch (e) {
      value = value.copyWith(errorDescription: e.message);
      throw new CameraException(e.code, e.message);
    }

    BarcodeScanner._channel.setMethodCallHandler((MethodCall call){
      if(call.method == "barcodeDetected"){
        String barcode = call.arguments;
        debounce(2500, this.handler, [barcode]);
      }
    });

    _creatingCompleter.complete(null);
  }

  void _applyStartStop() {
    if (value.initialized && !_disposed) {
      if (value.isStarted) {
        BarcodeScanner.startCamera();
      } else {
        BarcodeScanner.stopCamera();
      }
    }
  }

  /// Starts the preview.
  ///
  /// If called before [initialize] it will take effect just after
  /// initialization is done.
  void start() {
    value = value.copyWith(isStarted: true);
    _applyStartStop();
  }

  /// Stops the preview.
  ///
  /// If called before [initialize] it will take effect just after
  /// initialization is done.
  void stop() {
    value = value.copyWith(isStarted: false);
    _applyStartStop();
  }

  /// Releases the resources of this camera.
  @override
  Future<Null> dispose() {
    if (_disposed) {
      return new Future<Null>.value(null);
    }
    _disposed = true;
    super.dispose();
    if (_creatingCompleter == null) {
      return new Future<Null>.value(null);
    } else {
      return _creatingCompleter.future.then((_) async {
        BarcodeScanner._channel.setMethodCallHandler(null);
        await BarcodeScanner.disposeCamera();
      });
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

hen*_*dra 6

我最终停止了,controller然后才导航到另一页并重新启动它pop()(称为)。

//navigate to new page
void didDetectBarcode(String barcode) {
   controller.stop();
   Navigator.of(context)
       .push(...)
       .then(() => controller.start()); //future completes when pop() returns to this page

}
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是将打开的maintainState属性设置为。routeScanPagefalse