'Not able to display the value of a variable defined out of a widget
i'm new to dart and i'm trying to display the file name inside the Text widget! I first took out the file's name inside the onPressed function, but later on couldn't access it in order to display it, can anyone help me out with this issue? thank in advance.
Here is my code:
body: Column(
children: [
ElevatedButton(
onPressed: () async {
final result = await FilePicker.platform.pickFiles();
if (result == null) return;
final file = result.files.first;
/* print(file.extension);
print(file.name); */
final FileName = file.name;
final newFile = await saveFilePermanently(file);
print('Old: ${file.path}');
print('New: ${newFile.path}');
},
child: const Text('Name: ')),
],
),
Solution 1:[1]
You need to create a variable to store the file name outside your onPressed method and use setState() to update your variable value.
String fileName = '';
...
body: Column(
children: [
ElevatedButton(
onPressed: () async {
final result = await FilePicker.platform.pickFiles();
if (result == null) return;
final file = result.files.first;
/* print(file.extension);
print(file.name); */
final FileName = file.name;
final newFile = await saveFilePermanently(file);
print('Old: ${file.path}');
print('New: ${newFile.path}');
// add this setState to update your variable value
setState(() {
fileName = newFile.path;
});
},
child: const Text('Name: $fileName')), // show your value here
],
),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Henrique Zanferrari |
