You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Image Compress调用报错toLowerCase called on null如何解决?

Flutter Image Compress toLowerCase空指针报错解决方案

触发原因

从报错堆栈可以定位到错误出现在flutter_image_compress库的Validator.checkFileNameAndFormat方法中:
你代码中仅声明了targetPath变量但未进行赋值,传入compressAndGetFile方法的targetPath参数为null,库内部在校验输出文件路径时,尝试对null值调用toLowerCase()方法,直接触发空指针异常。

解决方法

  • 给targetPath赋值合法的输出文件路径,你可以配合path_provider库获取设备可读写的目录,拼接生成合法输出路径,示例代码如下:
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

// 生成合法输出路径
Directory tempDir = await getTemporaryDirectory();
String targetPath = path.join(tempDir.path, "compressed_${DateTime.now().millisecondsSinceEpoch}.webp");

// 调用压缩方法
var result = await FlutterImageCompress.compressAndGetFile(
  img.path,
  targetPath,
  quality: 88,
  format: CompressFormat.webp,
);
  • 如果需要自定义输出目录,直接指定已获取读写权限的目录下的完整文件路径,确保路径不为空,且包含与压缩格式匹配的文件后缀。
  • 如果你不需要自定义输出路径,可直接调用库中无需传入targetPath的压缩API,压缩完成后库会自动生成临时路径返回。

内容的提问来源于stack exchange,提问作者zerochill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 07:15:04