首页 > 解决方案 > 当我仅在 iOS 设备中使用 image_picker 和 image_crop 库时,State 的 build() 方法会被调用

问题描述

当我从图库中选择图像并想要执行进一步操作时,我正在使用这两个库从图库或相机( image_picker 和 image_cropper )中挑选和裁剪图像,然后自动调用build方法并更改我的代码流。

在 android 设备中,此代码运行良好,并且build仅调用一次方法,但在 iOS 设备build中,当我从图库中选择图像并裁剪此图像后会调用此方法。

在 iOS 设备中,当设备的照片库打开build时,调用方法,当调用裁剪时,再次build调用 Drawer 类的方法。

这个问题只发生在 Drawer 中,如果我调用我的 TextRobo 类,Navigator.of(context).pushReplacementNamed('/textRobo');那么这工作正常。

抽屉类

_getDrawerItemWidget(int pos, String title) {


  switch (pos) {
    case 0:
      if(title.contains("From Gallery"))

        return new TextRobo();
      if(title.contains("From Camera"))
        return new TextRoboCamera();
      else if(widget.fragment_class.contains("Translate"))
        return new TranslateLangue(widget.textToTranslate);
      else
        return new TranslateLangue("");


      break;

    case 1:

      if(title.contains("From Gallery"))
        return new BarCodeRobo();
      else
        return new BarCodeQuick();

      break;
    case 2:
      return new TranslateLangue("");

  //default:
  //return new TranslateLangue("");
  }


}

@override
Widget build(BuildContext context) {

print('Building widget');


return new Scaffold(

appBar: new AppBar(
  iconTheme: new IconThemeData(color: Colors.white),
  title: new Text("RoboScan",
    style: new TextStyle(color: Colors.white),),
),

  drawer: new Drawer(
    child: new ListView(
      children: <Widget>[
        new Container( height: 140.0, color: Colors.orange,
        child: new Center(child:
          new Text('RoboScan', style: new TextStyle(color: Colors.white,
          fontSize:25.0, fontWeight: FontWeight.bold),
          ),
        ),
        ),
        new Column(
            children: drawerOptions)
      ],
    ),

  ),
  body: _getDrawerItemWidget(_selectedDrawerIndex, widget.fragment_class  ),
);
}

图像选择器和裁剪类(TextRobo)

 File _imageFile;
 List<VisionText> _currentTextLabels = <VisionText>[];
 FirebaseVisionTextDetector textDetector = 
 FirebaseVisionTextDetector.instance;


 @override
 void initState() {
 // TODO: implement initState
//scanImage();
 super.initState();

 _getAndScanImage();

 }


Future<void> _getAndScanImage() async {
setState(() {
  _imageFile = null;
 // _imageSize = null;
});

 final File imageFile =
 await ImagePicker.pickImage(source: ImageSource.gallery);


 _cropImage(imageFile);

}

标签: dartflutter

解决方案


小部件的build方法旨在频繁调用。我建议您重新构造事物,以便根据 Flutter 框架的要求调用您的构建方法。

注意:最好将“状态”推到树下尽可能远的地方(朝向叶子小部件),以最大限度地减少由于状态变化而导致的小部件重建的影响。

在您的情况下,您可能需要考虑_getAndScanImage()从该initState方法中删除。让你的渲染流影响你的交互不是一个好的模式。

您可以尝试_getAndScanImage()通过按钮按下或其他一些用户触发操作而不是渲染生命周期来触发该方法initState吗?


推荐阅读