从插件回调导航

时间:2018-04-16 22:18:52

标签: flutter

问题是当我想从回调中导航时 - 由插件调用 - 新页面作为我页面中的小部件被推入。

这是代码:

import 'dart:async';

import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyApp(),
  ) );
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String barcode = "";

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

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
          appBar: new AppBar(
            title: new Text('Barcode Scanner Example'),
          ),
          body: new Center(
            child: new Column(
              children: <Widget>[
                new Container(
                  child: new MaterialButton(
                      onPressed: scan, child: new Text("Scan")),
                  padding: const EdgeInsets.all(8.0),
                ),
              ],
            ),
          ));
  }

  Future scan() async {
    try {
      String barcode = await BarcodeScanner.scan();
      print("${context}");
      Navigator.push(context, MaterialPageRoute(
          builder: (context) {
            return new BarcodePage(barcode);}
          ));

      setState(() => this.barcode = barcode);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          this.barcode = 'The user did not grant the camera permission!';
        });
      } else {
        setState(() => this.barcode = 'Unknown error: $e');
      }
    } on FormatException{
      setState(() => this.barcode = 'null (User returned using the "back"-button before scanning anything. Result)');
    } catch (e) {
      setState(() => this.barcode = 'Unknown error: $e');
    }
  }
}

class BarcodePage extends StatefulWidget {
  BarcodePage(String s) {
    str = s;
  }
  String str;
  @override
  State<StatefulWidget> createState() {
    return _BarcodePageState(str);
  }

}
class _BarcodePageState extends State<BarcodePage> {
    String str;

  _BarcodePageState(String s ){
    str = s;

  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar:  new AppBar(title: new Text("Bar code"),),
      body: new Text(str),
    );
  }

}

您可以在https://github.com/arashbi/flutter_barcode_reader示例文件夹

中找到该应用程序

这与之前的问题有关,但设置更简单。

1 个答案:

答案 0 :(得分:0)

AFAI理解问题是回调是在渲染管道中发生的,它会导致错误的行为。解决方案是使用Future.delayedSchedulerBinding.instance.addPostFrameCallback

这些方法导致导航在渲染管道之后发生,导航器可以正常工作