I have this upLoadFile() void here and when I pick the file I want to display the fileName that I just picked FOR EX. "img89004.png" in the Text(fileName!) code:
String? fileName;
void upLoadFile() async {
final results = await FilePicker.platform.pickFiles(
allowMultiple: false,
type: FileType.custom,
allowedExtensions: ['jpg', 'png'],
);
final path = results!.files.single.path!;
final fileName = results.files.single.name;
storage.uploadFile(path, fileName);
print(fileName);
}
//I want to display the fileName that I just picked HERE
fileName == null
? const Center(child: Text('No file selected'))
: Center(child: Text(fileName!)),
//Button
onPressed: () async {
upLoadFile();
},
CodePudding user response:
This is a full example of what you need:
class FilePickerTest extends StatefulWidget {
const FilePickerTest({Key? key}) : super(key: key);
@override
State<FilePickerTest> createState() => _FilePickerTestState();
}
class _FilePickerTestState extends State<FilePickerTest> {
String _fileName = '';
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(_fileName),
InkWell(
onTap: () {
upLoadFile();
},
child: Text('Select file'),
),
SizedBox(
height: 16,
),
InkWell(
onTap: () {
setState(() {
_fileName = '';
});
},
child: Text('Clear'),
),
],
);
}
void upLoadFile() async {
final results = await FilePicker.platform.pickFiles(
allowMultiple: false,
type: FileType.custom,
allowedExtensions: ['jpg', 'png'],
);
if (results != null) {
final path = results!.files.single.path!;
_fileName = results.files.single.name;
storage.uploadFile(path, fileName);
setState(() {});
print(_fileName);
} else {
// User canceled the picker
}
}
}
CodePudding user response:
It should be this way
final fileName = path.split('/').last;
print(fileName);
the name contains the extension type