使用文件选择器时现有文件是否颤抖?

Existing file in flutter when using file picker?

我正在研究 flutter。我实现了 filePicker(),以选择文件并将它们显示在 listView 中。我想知道我们如何检查列表中已经存在的文件。因此,文件选择器无法再次添加以前存在的文件。代码附在下面。如果有人帮助,我很高兴。

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,
        ),
      ),
    );
  }
}

试试这个..

先放路径

// 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
  }
}

if (result != null) {
  files.add(result.paths.map((e) => File(e!)).toSet().toList());
} else {
  // Leave this blank if the user didn't pick some
}