简体   繁体   中英

Checking the existing file in flutter using file picker?

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.

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';

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

you can delete directly according to the index list that is intended,

one of the examples I use

 Future<void> deleteList(idx) async { print('delete'); _classList.removeAt(idx); print(_classListSection); // images.clear(); String error = 'No Error Detected'; setState(() { _classList = _classList; _count--; // _error = error; }); }

in your case this is the following list "files";

在此处输入图像描述

Here we save file location in the item list after checking the file exists. if a file exists we show the snackbar widget.

 List item = [];
  List<Widget> widgets = [];

  Future<void> Filepick(context) async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
        //here the checking works---------------------->
      var path2 = result.files.single.path;
      if (!item.contains(path2)) {
        item.add(path2);
        File file = File(path2 ?? "");
        setState(() {
          widgets
              .add(SizedBox(height: 100, width: 100, child: Image.file(file)));
        });
      } else {
        // Scaffold.of(globalkey2.currentContext??context)
        globalkey2.currentState
            ?.showSnackBar(SnackBar(content: Text("File Already Exist")));
      }
    } else {
      // User canceled the picker
    }
  }

FullCode

import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(MaterialApp( home: sta()));
}


class sta extends StatefulWidget {
  sta({Key? key}) : super(key: key);

  @override
  State<sta> createState() => _staState();
}

class _staState extends State<sta> {
  GlobalKey<ScaffoldState> globalkey2 =
      GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
 
    return Scaffold(
        key: globalkey2,
        appBar: AppBar(),
        body: Container(
          height: 750,
          child: Column(
            // mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Align(
                  alignment: Alignment.center,
                  child: Container(
                    height: 100,
                    width: 100,
                    child: OutlinedButton(
                      onPressed: () {
                        Filepick(context);
                      },
                      child: Text("Pick File"),
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: MediaQuery.of(context).size.height - 200,
                child: GridView.count(
                  mainAxisSpacing: 4,
                  crossAxisCount: 2,
                  children: [...widgets],
                ),
              ),

              // ...widgets
            ],
          ),
        ));
  }

  List item = [];
  List<Widget> widgets = [];

  Future<void> Filepick(context) async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      var path2 = result.files.single.path;
      if (!item.contains(path2)) {
        item.add(path2);
        File file = File(path2 ?? "");
        setState(() {
          widgets
              .add(SizedBox(height: 100, width: 100, child: Image.file(file)));
        });
      } else {
        // Scaffold.of(globalkey2.currentContext??context)
        globalkey2.currentState
            ?.showSnackBar(SnackBar(content: Text("File Already Exist")));
      }
    } else {
      // User canceled the picker
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM