dart - 当我仅在 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);
}
解决方案
小部件的build
方法旨在频繁调用。我建议您重新构造事物,以便根据 Flutter 框架的要求调用您的构建方法。
注意:最好将“状态”推到树下尽可能远的地方(朝向叶子小部件),以最大限度地减少由于状态变化而导致的小部件重建的影响。
在您的情况下,您可能需要考虑_getAndScanImage()
从该initState
方法中删除。让你的渲染流影响你的交互不是一个好的模式。
您可以尝试_getAndScanImage()
通过按钮按下或其他一些用户触发操作而不是渲染生命周期来触发该方法initState
吗?
推荐阅读
- sql - 使用 LEAD 函数提取数据减去天数
- here-api - 中国的ADS数据?
- r - 关于在组内和时间方面造成滞后的两个问题
- javascript - 确定一个值是否是完美正方形,如果是,则将其推入一个空数组
- python - 在 python 中创建轮盘赌模拟器
- c# - HttpContext.Current.Session 在调用 Web 方法时抛出了 System.NullReferenceException 类型的异常
- r - 卡住 - 按分组排序
- c# - 验证从 1 开始的正整数的 id 路由参数
- hadoop - HADOOP:无法运行 hdfs namenoe -format
- powershell - 将值传递给powershell脚本中的函数