Flutter安卓端选Excel文件触发空值检查错误,Web端正常求解决
问题解决:Flutter安卓端选择Excel文件时的空指针异常
错误根源
Web端因平台特性会自动将文件内容加载到bytes属性,但安卓平台下FilePicker默认不会主动读取文件内容到bytes,导致你强制解包bytes!时触发Null check operator used on a null value异常。
解决方案
1. 修改FilePicker调用,强制加载文件内容
在pickFiles方法中添加withData: true参数,让安卓端也将文件内容加载到bytes中:
var pickedFile = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: ['xlsx'], allowMultiple: false, withData: true, // 新增此参数,强制加载文件内容到bytes );
2. 添加Null安全检查,避免崩溃
即使添加了withData: true,仍可能因文件过大、权限问题导致bytes为null,建议在dataSend方法中增加判断:
dataSend(FilePickerResult pickedFile, String site, String appareil, String debutLocation, String finLocation) async { // 注意添加async CollectionReference sewsDatabase = FirebaseFirestore.instance.collection('sewsDatabase'); List<String> rowdetail = []; int? col; var bytes = pickedFile.files.single.bytes; // 新增Null检查 if (bytes == null) { // 可替换为SnackBar或弹窗提示用户 print("文件读取失败,请检查文件完整性或权限"); return; } var excel = Excel.decodeBytes(bytes); // 无需再强制解包 var nSerie = []; for (var table in excel.tables.keys) { try { for (var row in excel.tables[table]!.rows) { rowdetail.add(row.elementAt(0)!.value.toString()); col = row.length; } print(rowdetail); } on Exception catch (e) { print(e); } } }
3. 检查安卓权限配置
针对Android 13以下版本,需在android/app/src/main/AndroidManifest.xml中添加文件读取权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Android 13+版本无需额外配置,FilePicker会自动请求媒体权限。
备选方案:通过文件路径读取(适合大文件)
如果Excel文件较大,使用withData: true可能导致内存占用过高,可改用文件路径读取:
// 修改pickFiles,不加载bytes var pickedFile = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: ['xlsx'], allowMultiple: false, withData: false, // 不加载到内存,仅获取路径 ); // 在dataSend中通过路径读取字节 var path = pickedFile.files.single.path; if (path != null) { var bytes = await File(path).readAsBytes(); var excel = Excel.decodeBytes(bytes); // 后续逻辑不变 }
内容的提问来源于stack exchange,提问作者badreddine afyf
相关产品推荐
相关产品推荐

