简体   繁体   English

未选中时处理文件路径在 flutter?

[英]Handle File path in flutter when not selected?

My issue in below code is to fail to handle null path when file is not selected.我在下面代码中的问题是在未选择文件时无法处理 null 路径。 I have 2 slider images picker file.我有 2 个 slider 图像选择器文件。 If i select 1 and dont select other it gives null path error how to handle it in order to post it successfully?如果我 select 1 而不是 select 其他它给出null 路径错误如何处理它才能成功发布? And i need that if i dont select anyone from these 2 files so it wont be posted by.我需要,如果我没有 select 来自这 2 个文件的任何人,那么它就不会被发布。

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:pursattm/utils/utils.dart';

class ImagesAddPage extends StatefulWidget {
  @override
  _ImagesAddPageState createState() => _ImagesAddPageState();
}

class _ImagesAddPageState extends State<ImagesAddPage> {
  Padding popUpAboveText(String text) {
    return Padding(
      padding: EdgeInsets.fromLTRB(0, 25, 0, 0),
      child: Align(
        alignment: Alignment.centerLeft,
        child: Text(
          text.toUpperCase(),
        ),
      ),
    );
  }

  //other images
  File sliderImage1;
  File sliderImage2;
  File sliderImage3;
  Widget buildGridView() {
    return GridView.count(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      crossAxisCount: 3,
      childAspectRatio: 1.6,
      children: [
        sliderImage1 != null
            ? Card(
                clipBehavior: Clip.antiAlias,
                child: Stack(
                  children: <Widget>[
                    Image.file(
                      sliderImage1,
                      width: 300,
                      height: 350,
                      fit: BoxFit.fill,
                    ),
                    Positioned(
                      right: 2,
                      top: 2,
                      child: InkWell(
                        onTap: () {
                          setState(() {
                            sliderImage1 = null;
                          });
                        },
                        child: Container(
                          margin: const EdgeInsets.all(3),
                          decoration: BoxDecoration(
                            color: Colors.grey.withOpacity(.7),
                            shape: BoxShape.circle,
                          ),
                          alignment: Alignment.center,
                          height: 21,
                          width: 21,
                          child: Icon(
                            Icons.close,
                            size: 16,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              )
            : Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: AppColors.LINE_COLOR, width: 1.5),
                    color: AppColors.GREEN.withOpacity(0.1),
                  ),
                  child: IconButton(
                    icon: Icon(
                      Icons.camera_enhance,
                      size: 22,
                      color: AppColors.GREEN,
                    ),
                    onPressed: _addSliderImage1,
                  ),
                ),
              ),
        sliderImage2 != null
            ? Card(
                clipBehavior: Clip.antiAlias,
                child: Stack(
                  children: <Widget>[
                    Image.file(
                      sliderImage2,
                      width: 300,
                      height: 350,
                      fit: BoxFit.fill,
                    ),
                    Positioned(
                      right: 2,
                      top: 2,
                      child: InkWell(
                        onTap: () {
                          setState(() {
                            sliderImage2 = null;
                          });
                        },
                        child: Container(
                          margin: const EdgeInsets.all(3),
                          decoration: BoxDecoration(
                            color: Colors.grey.withOpacity(.7),
                            shape: BoxShape.circle,
                          ),
                          alignment: Alignment.center,
                          height: 21,
                          width: 21,
                          child: Icon(
                            Icons.close,
                            size: 16,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              )
            : Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: AppColors.LINE_COLOR, width: 1.5),
                    color: AppColors.GREEN.withOpacity(0.1),
                  ),
                  child: IconButton(
                    icon: Icon(
                      Icons.camera_enhance,
                      size: 22,
                      color: AppColors.GREEN,
                    ),
                    onPressed: _addSliderImage2,
                  ),
                ),
              ),
        sliderImage3 != null
            ? Card(
                clipBehavior: Clip.antiAlias,
                child: Stack(
                  children: <Widget>[
                    Image.file(
                      sliderImage3,
                      width: 300,
                      height: 350,
                      fit: BoxFit.fill,
                    ),
                    Positioned(
                      right: 2,
                      top: 2,
                      child: InkWell(
                        onTap: () {
                          setState(() {
                            sliderImage3 = null;
                          });
                        },
                        child: Container(
                          margin: const EdgeInsets.all(3),
                          decoration: BoxDecoration(
                            color: Colors.grey.withOpacity(.7),
                            shape: BoxShape.circle,
                          ),
                          alignment: Alignment.center,
                          height: 21,
                          width: 21,
                          child: Icon(
                            Icons.close,
                            size: 16,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              )
            : Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(color: AppColors.LINE_COLOR, width: 1.5),
                    color: AppColors.GREEN.withOpacity(0.1),
                  ),
                  child: IconButton(
                    icon: Icon(
                      Icons.camera_enhance,
                      size: 22,
                      color: AppColors.GREEN,
                    ),
                    onPressed: _addSliderImage3,
                  ),
                ),
              ),
      ],
    );
  }

  Future _addSliderImage1() async {
    final pickImage = ImagePicker();
    var _imageFile = await pickImage.getImage(source: ImageSource.gallery);
    setState(() {
      sliderImage1 = File(_imageFile.path);
    });
  }

  Future _addSliderImage2() async {
    final pickImage = ImagePicker();
    var _imageFile = await pickImage.getImage(source: ImageSource.gallery);
    setState(() {
      sliderImage2 = File(_imageFile.path);
    });
  }

  Future _addSliderImage3() async {
    final pickImage = ImagePicker();
    var _imageFile = await pickImage.getImage(source: ImageSource.gallery);
    setState(() {
      sliderImage3 = File(_imageFile.path);
      //_cropSliderImage3(sliderImage3);
    });
  }

  final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
  bool _autovalidate = false;
  final _nameController = TextEditingController();

  // form variables
  FormData formData;

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        title: Text(
          'Title',
        ),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            size: 25,
            color: AppColors.GREEN_MAIN,
          ),
          onPressed: () {
            NavUtils.pop(context);
          },
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: FormBuilder(
            key: _fbKey,
            autovalidate: _autovalidate,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                popUpAboveText('Select Images'),
                SizedBox(height: 10),
                buildGridView(),
                SizedBox(height: 25),
                popUpAboveText('Name'),
                FormBuilderTextField(
                  attribute: 'name',
                  controller: _nameController,
                  validators: [
                    FormBuilderValidators.required(errorText: 'Give Name!')
                  ],
                  style: TextStyle(color: AppColors.GREEN),
                ),

                // mainButton
                const SizedBox(height: 20.0),
                RawMaterialButton(
                  child: Text('Press to send'),
                  onPressed: () async {
                    if (_fbKey.currentState.saveAndValidate()) {
                      print(_fbKey.currentState.value);
                      if (sliderImage1 == null) {
                        toastMessage('Choose minimum 1 image');
                      } else {
                        String image1FileName =
                            sliderImage1.path.split('/').last;
                        String image2FileName =
                            sliderImage2.path.split('/').last;
                        String image3FileName =
                            sliderImage3.path.split('/').last;

                        // form list
                        formData = FormData.fromMap({
                          'name': _nameController.text,
                          'slider_images': [
                            await MultipartFile.fromFile(sliderImage1.path,
                                filename: image1FileName),
                            sliderImage2.path ==
                                    null // how to handle null error so that it wont post this sliderImage 2
                                ? ''
                                : await MultipartFile.fromFile(
                                    sliderImage2.path,
                                    filename: image2FileName),
                            sliderImage3.path ==
                                    null // how to handle null error so that it wont post this sliderImage 3
                                ? ''
                                : await MultipartFile.fromFile(
                                    sliderImage3.path,
                                    filename: image3FileName),
                          ],
                        });

                        // posting form
                        // finally post form
                      }
                    } else {
                      setState(() {
                        _autovalidate = true; //enable realtime validation
                      });
                      print('validation failed');
                    }
                  },
                ),
                const SizedBox(height: 10.0),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void toastMessage(String message) {
    Fluttertoast.showToast(
        msg: message,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 1,
        fontSize: 16.0);
  }
}

Problem问题

Here you are checking for path if that's null like this:如果是 null,您将在此处检查路径,如下所示:

sliderImage.path == null ? something else : Process image

which in case sliderImage is null will generate exception.如果 sliderImage 是 null 将产生异常。

Solution解决方案

Check for sliderImage if that's null or not instead of the path.检查 sliderImage 是否为 null 而不是路径。 Do it as below:如下所示:

sliderImage == null ? something else : Process image

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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