FilePicker- path[] - list empty



我正在开发一个视图,用户可以在其中单击按钮-图片,然后用户应该能够选择一个图像。然后,用户可能希望再次单击并选择其他图像。第二个图像应该添加到前一个图像上。应同时显示这两个图像。下面,你会看到我做了几个测试,但都不起作用。在第一种情况下,我无法逐个存储图像。在第二种情况下,我收到一条错误消息";在解析图像编解码器时引发了以下FileSystemException:无法打开文件,路径="[]"(操作系统错误:没有这样的文件或目录,错误号=2(">

我已经更新了我的代码。我在代码的两个不同位置添加了打印。第一次打印,显示正确的结果。第二个显示所有值为空或null。这很奇怪。我不明白为什么。

如果你能帮我,那就太好了。

import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
class FilePickerDemo extends StatefulWidget {
@override
_FilePickerDemoState createState() => _FilePickerDemoState();
}
class _FilePickerDemoState extends State<FilePickerDemo> {
//FirebaseStorage storage = FirebaseStorage.instance;
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
late String _fileName;
List<PlatformFile>? _paths;
List<PlatformFile>? _allFile;
bool _loadingPath = false;
bool _multiPick = true;
List<String>? extensions;
FileType _fileType = FileType.media;
List<File> f = [];
var image;
List<File> filesGB =[];

String _file_Type_pdf_image = '';
void _openPictureFileExplorer() async {
setState(() => _loadingPath = true);
/*
FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);
if(result != null) {
List<File> files = result.paths.map((path) => File(path!)).toList();
} else {
// User canceled the picker
}
*/
try {
//####################################################
// _paths = (await FilePicker.platform.pickFiles(
//   type: _fileType,
//   allowMultiple: _multiPick,
// ))
//     ?.files;
//####################################################
FilePickerResult? _paths = await FilePicker.platform.pickFiles(
type: _fileType,
allowMultiple: _multiPick,
);
if (_paths != null) {
List<File> filesGB = _paths.paths.map((path) => File(path!)).toList();
setState(() {});
print('File Name:'+filesGB.toString());
print ('# record:'+ filesGB.length.toString());
print ('Empty?: '+filesGB.isEmpty.toString());
}
/*
//######################################################
FilePickerResult? result = await FilePicker.platform.pickFiles(
allowMultiple: true,
type: _fileType,
);
if (result != null) {
List<File> filesGB = result.paths.map((path) => File(path!)).toList();
setState(() {});
print('mon Fichier:'+filesGB.toString());
}
//####################################################
*/
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
} catch (ex) {
print('$ex');
}
//if (!mounted) return;
setState(() {
_loadingPath = false;
//print(_paths!.last.name);
print('File Name:'+filesGB.toString());
print ('# record:'+ filesGB.length.toString());
print ('Empty?: '+filesGB.isEmpty.toString());
_fileName = _paths != null ?
_paths!.map((e) => e.name).toString() : '...';
});
}
/*
void _openDocumentFileExplorer({fileType: FileType.custom}) async {
setState(() => _loadingPath = true);
extensions == ['pdf', 'PDF'];
try {
_paths = (await FilePickerDemo.platform.pickFiles(
type: fileType,
allowMultiple: true, //_multiPick,
allowedExtensions: ['pdf', 'doc']
))
?.files;
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
} catch (ex) {
print('$ex');
}
if (!mounted) return;
setState(() {
_loadingPath = false;
//  print(_paths!.last.name);
_fileName = _paths != null ?
_paths!.map((e) => e.name).toString() : '...';
if (_paths != null) {
_allFile!.addAll(_paths!);
// print(_allFile);
}
});
}
void _clearCachedFiles() {
FilePickerDemo.platform.clearTemporaryFiles().then((result) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: result! ? Colors.green : Colors.red,
content: Text((result
? 'Temporary files removed with success.'
: 'Failed to clean temporary files')),
),
);
});
}
*/
/*
void imagem() async {
PickedFile? picked = await ImagePicker().getImage(
preferredCameraDevice: CameraDevice.front, source: ImageSource.gallery);
setState(() {
image = File(picked!.path);
Image.file(image);
});}
*/
// Select and image from the gallery or take a picture with the camera
// Then upload to Firebase Storage
/*
Future<void> _upload() async {
try {
final String fileName = _fileName;
File imageFile = File(_paths.toString());
try {
// Uploading the selected image with some custom meta data
await storage.ref(fileName).putFile(
imageFile,
);
// Refresh the UI
setState(() {});
} on FirebaseException catch (error) {
print(error);
}
} catch (err) {
print(err);
}
}

*/

// Delete the selected image
// This function is called when a trash icon is pressed
void _delete(int index) {
if (_paths != null || _paths!.length > 1) {
_paths!.removeAt(index);
setState(() {});
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: const Text('File Picker example app'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.only(left: 10.0, right: 10.0),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 20.0),
//#############
//Affiche card avec button pour selectionner type de piece jointe - photo ou docuent ou audio record
child: Card(
child:
Container(
// color: Colors.red,
alignment: Alignment.center,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FlatButton(
onPressed: () {},
child:
InkWell(
child: Container(
//  color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment
.center,
children: [
Icon(Icons.access_alarm_outlined),
Text('TEST'),
],
)
),
onTap: () {
_file_Type_pdf_image = 'pdf';
//imagem;
},
),
),
//Attachement
FlatButton(
onPressed: () {},
child:
InkWell(
child: Container(
//  color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment
.center,
children: [
Icon(Icons.attach_file),
Text('Attachement'),
],
)
),
onTap: () {
_file_Type_pdf_image = 'pdf';
//_openDocumentFileExplorer();
},
),
),
//Photo
FlatButton(
onPressed: () {},
child:
InkWell(
child: Container(
//   color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment
.center,
children: [
Icon(Icons.add_a_photo_rounded),
Text('Photo'),
],
)
),
onTap: () {
_file_Type_pdf_image = 'jpeg';
_openPictureFileExplorer();
},
),
),
],
),
)),
),

Builder(
builder: (BuildContext context) =>
_loadingPath ?
Padding(
padding: const EdgeInsets.only(bottom: 10.0),
child: const CircularProgressIndicator(),
)
: _paths != null && _paths!.isNotEmpty
? Container(
padding: const EdgeInsets.only(bottom: 30.0),
height:
MediaQuery
.of(context)
.size
.height * 0.50,
child: Scrollbar(
child: _paths!.isNotEmpty ?
ListView.separated(
itemCount:
_paths != null && _paths!.isNotEmpty
? _paths!.length
: 1,
itemBuilder:
(BuildContext context, int index) {
final bool isMultiPath =
_paths != null && _paths!.isNotEmpty;
final String name =
_paths!
.map((e) => e.name)
.toList()[index];
final path = _paths!
.map((e) => e.path)
.toList()[index]
.toString();
return Container(
height: 114,
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
elevation: 10,
child: ClipPath(
clipper: ShapeBorderClipper(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius
.circular(15))),
child: Row(
crossAxisAlignment: CrossAxisAlignment
.center,
mainAxisAlignment: MainAxisAlignment
.start,
children: [
Container(
height: 113, width: 113,
child: _file_Type_pdf_image == 'pdf'
?
Image.asset("assets/logo_pdf.png")
// fit: BoxFit.fill,
// width: double.infinity,):
: Image.file(File(f.toString()),
fit: BoxFit.fill,
width: double.infinity,),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(
10.0),
child: Text(name,
style: TextStyle(
fontWeight: FontWeight
.bold),),
),
),
Padding(
padding: const EdgeInsets.only(
right: 25.0),
child: IconButton(onPressed: () {
//delete a record and the card displaying this record
_delete(index);
},
icon: Icon(Icons.delete,
color: Colors.red,),),
)
],
),
),
//subtitle: Text(path),
),
);
},
separatorBuilder:
(BuildContext context, int index) =>
const SizedBox(),) : Text(
"Text to display when _paths is empty"),),)
: filesGB.isEmpty? SizedBox(child:image= (Image.file(File(filesGB.toString())))): Text('ALL Empty'),//child: Text('No documents')),
),
],
),
),
)),
),
);
}
}

我没有仔细阅读您的代码,但我仍然可以建议您首先更新您的包,或者尝试使用不同的包。使用列表存储图像数据。在实际设备上进行测试。

最新更新