Heres my code where it can pick the file
FilePickerResult? result;
String _fileName = '';
PlatformFile? pickedfile;
File? fileToDisplay;
Continuation of the code :
void pickFile() async {
try {
result = (await FilePicker.platform
.pickFiles(type: FileType.any, allowMultiple: false))!;
if (result != null) {
List<File> files = result!.paths.map((path) => File(path!)).toList();
_fileName = result!.files.first.name;
pickedfile = result!.files.first;
fileToDisplay = File(pickedfile!.path.toString());
}
} catch (e) {
print(e);
}
}
My Code that i want to display in the UI which is after i clicking the file, the name of file will display in UI
ElevatedButton(
onPressed: () {
pickFile();
},
style: ElevatedButton.styleFrom(
minimumSize: const Size(71, 28),
backgroundColor: Color(0xFFAECAD6),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4),
),
),
label: Text(
'Add File',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
color: Colors.black),
),
),
],
),
Code where it display the text
Column(
children: [
Container(
height: 150,
width: double.infinity,
color: Colors.white,
child: Text(_fileName))
],
),
CodePudding user response:
You need to wait for the file picker to choose the file and then update the state. To wait for any specific code you just need to add async keyword before the code but that method or code should be of future. To update the state, use setState function. Make the following changes to your pickFile function and onTap function of GestureDetector.
pickFile() :-
Future<void> pickFile() async { // add Future keyword.
try {
result = (await FilePicker.platform
.pickFiles(type: FileType.any, allowMultiple: false))!;
if (result != null) {
List<File> files = result!.paths.map((path) => File(path!)).toList();
_fileName = result!.files.first.name;
pickedfile = result!.files.first;
fileToDisplay = File(pickedfile!.path.toString());
}
} catch (e) {
print(e);
}
}
onTap : -
onTap: (() async {
await pickFile(); // wait for the file.
setState(() {});
}),
Output : -