Flutter中DrawerHeader的CircleAvatar更换本地图片报错求助
问题原因 & 解决办法
核心错误
你用AssetImage加载设备文件系统里的图片路径是错的——AssetImage只能加载项目assets目录下、且在pubspec.yaml中声明过的资源文件,不能直接读取设备本地的文件路径,这就是报错的根源。
解决步骤
- 把状态变量的类型从
AssetImage改成ImageProvider(AssetImage和FileImage都是它的子类,能同时兼容默认资源图和本地文件图) - 选中图片后,用
FileImage替代AssetImage来加载本地文件
修正后的代码
ImageProvider image = AssetImage('assets/images/profile-user.png'); pickNewImage() async { final status = await Permission.storage.status; String folderPath = ""; if (status != PermissionStatus.granted) { await Permission.storage.request(); } if (await Permission.storage.status.isGranted) { Directory folderDir = await getApplicationDocumentsDirectory(); folderPath = folderDir.path; } final picker = ImagePicker(); final pickedImage = await picker.pickImage(source: ImageSource.gallery); if (pickedImage != null) { File pickedImageFile = File(pickedImage.path); final targetFile = File("$folderPath/profile-picked-user.png"); await pickedImageFile.copy(targetFile.path); setState(() { // 改用FileImage加载本地文件 image = FileImage(targetFile); }); } else { return; } }
额外提示
- 若你的App适配Android 13及以上版本,建议改用
Permission.photos(或READ_MEDIA_IMAGES)权限,比storage权限更适配新版本系统权限规则 - 可以打印
targetFile.path确认路径是否和你手动检查的目录一致,避免路径拼接错误
内容的提问来源于stack exchange,提问作者Luis Rotoly
相关产品推荐
相关产品推荐

