I am working with flutter. I implement filePicker(), to choose files and show them in a listView. I want to know how we check the already existing file in a list. So, the file picker can't add a previously existing file again. The code is attached below. I am glad if someone helps.
class pickFile extends StatefulWidget {
const pickFile({Key? key}) : super(key: key);
@override
State<pickFile> createState() => _pickFileState();
}
class _pickFileState extends State<pickFile> {
List<PlatformFile> files = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Add"),
actions: [
IconButton(
icon: const Icon(Icons.add),
onPressed: () async {
final result = await FilePicker.platform
.pickFiles(withReadStream: true, allowMultiple: true);
if (result == null) return;
files.add(result.files.first);
setState(() {});
},
),
],
),
body: Container(
width: 420,
height: 300,
child: show(
files: files,
),
),
);
}
}
CodePudding user response:
try this..
First put path
// This is not a package flutter have this just type this or copy
import 'package:path/path.dart' as path;
pickFiles() async {
final FilePickerResult? result = await FilePicker.platform
.pickFiles(type: FileType.media, allowMultiple: true);
if (result != null) {
// as your list named files
// this findDuplicate is determine that do we have a same name that was pick
final findDuplicate = result.path
.where((e1) =>
files.every((e2) => path.basename(e1!) != path.basename(e2.path)))
.toList();
// Identify first if we have already item inside
if (files.isNotEmpty) {
files.add(findDuplicate.map((e) => File(e!)).toList());
} else {
files.add(result.paths.map((e) => File(e!)).toList());
}
} else {
// Leave this blank if the user didn't pick some
}
}
or
if (result != null) {
files.add(result.paths.map((e) => File(e!)).toSet().toList());
} else {
// Leave this blank if the user didn't pick some
}