Flutter升级后ImagePicker拍照报错:需在主线程执行@UiThread方法
Hey there, I’ve run into a similar thread-related issue with plugin callbacks after Flutter updates, so let’s break this down and fix it!
问题原因分析
You’re right that Flutter’s async/await code typically runs on the main thread by default, but here’s the catch: some plugin operations (like the image picker’s post-capture callback) might be triggering on a background binder thread in newer Flutter versions. Even though your await call finishes, the code that processes the result might end up on the wrong thread—hence the @UiThread runtime error.
解决方案
We need to explicitly force the image processing logic back onto the main thread. Here are two reliable ways to do this:
方法1:使用WidgetsBinding.instance.addPostFrameCallback
This ensures your code runs right after the next frame is rendered, which is guaranteed to be on the main thread:
final File imageProduct = await ImagePicker.pickImage( source: ImageSource.camera, maxHeight: 1024, maxWidth: 1024 ); // 切换到主线程处理图片结果 WidgetsBinding.instance.addPostFrameCallback((_) { // 在这里执行你的图片操作,比如更新状态、显示图片等 setState(() { _selectedImage = imageProduct; }); });
方法2:使用Future.microtask
This queues your code to run on the main thread’s event loop immediately after the current task completes:
final File imageProduct = await ImagePicker.pickImage( source: ImageSource.camera, maxHeight: 1024, maxWidth: 1024 ); await Future.microtask(() { // 主线程操作逻辑 if (imageProduct != null) { // 处理图片的代码写在这里 } });
额外建议
Also, make sure your image_picker plugin version is compatible with Flutter v1.7.8+hotfix.3. Outdated plugins often have thread-handling mismatches with newer Flutter releases—check your pubspec.yaml and update to the latest plugin version that supports your Flutter SDK.
内容的提问来源于stack exchange,提问作者IMozes

