skip to Main Content

I am trying to work with a code where I want it to check if my file is not empty. When I try to do this:

void uploadProduct() {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      if (image != null) {
        setState(() {
          image = null;
        });
        _formKey.currentState!.reset();
      } else {
        snackBar('Please Pick Image', context);
      }
    } else {
      snackBar('Fields must not be empty', context);
    }
  }

What I am trying is to check whether or not if I have the file(image) selected or not, when I don’t have any image selected, it should show the snackBar (please pick image) as stated in the else, but it doesn’t work.

How can i fix it?

3

Answers


  1. Check for value is null or not

    if(_image != null) 
    
    Login or Signup to reply.
  2. If you have the path of the file, you can use dart:io

    var file = File('the_path_to_the_image');
    
    
    
    print(file.lengthSync()); 
    

    now check if length > 0 then file is not empty otherwise file is empty

    Login or Signup to reply.
  3. File not being empty isn’t very clear. There might be two conditions:

    1. File is null
      You can check it by:
    if(_image != null)
    
    1. If the file exists but it’s empty
      You can check that by:
    final _imageContent = await _image.readAsString();
    if(_imagContent.length > 0)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search