I am very new to flutter and coding. This may be an easy fix but I cannot find a solution anywhere or reconfigure the code to display the name of the file I am picking.
I am trying to create a web page that can accept document submissions. However, I cannot get the code to display the name of the file picked.
The print call is working, however, the fileNameSelected does not update.
Thank you for any help!!
import 'dart:html';
import 'dart:io' as io; //type cast
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:path/path.dart';
import './appbar/appbar.dart';
class UploadFPage extends StatefulWidget {
const UploadFPage({Key? key}) : super(key: key);
@override
State<UploadFPage> createState() => _UploadFPageState();
}
class _UploadFPageState extends State<UploadFPage> {
UploadTask? task;
File? file;
String fileNameSelected = 'No File Selected';
@override
Widget build(BuildContext context) {
final fileName = fileNameSelected;
return Scaffold(
appBar: AppBar(
title: const Text('AppBar'),
),
body: ListView(
children: [
Container(
height: 300,
color: Colors.amber,
child: Row(
children: [
ElevatedButton.icon(
icon: const Icon(Icons.attach_file, size: 28),
onPressed: selectFile,
label: Text("Attach Invoice"),
),
Text(fileName),
],
),
),
],
),
);
}
Future selectFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowMultiple: false,
allowedExtensions: ['pdf']);
if (result == null) {
return;
} else {
print(result.files.single.name);
//final name = result.files.single.name;
//final path = result.files.single.path!;
//final file = result.files.single.bytes!;
setState(() {
String fileNameSelected = basename(result.files.single.name);
//file = File(size, path);
});
}
}
}
CodePudding user response:
Change:
setState(() {
String fileNameSelected = basename(result.files.single.name);
});
to
setState(() {
fileNameSelected = basename(result.files.single.name);
});
By adding var
, final
or String
in front you are declaring a new variable (which happens to have the same name as the one you declared above). You assign your picked file to that - and it promptly goes out of scope.