如何在Flutter中从future函数返回值

sqxo8psd  于 2023-04-13  发布在  Flutter
关注(0)|答案(2)|浏览(154)

我创建了上传图像到应用程序的功能。所以我创建了共享相同onpressed()未来功能的重复按钮

class _HomePage5State extends State<HomePage5> {
  // This is the file that will be used to store the image
  File? _image;
  File? _image2;
  late String pickerType;
  // This is the image picker
  final _picker = ImagePicker();
  // Implementing the image picker
  Future _openImagePicker(String pickerType,File? pImage ) 

  async {
    
    XFile? pickedImage ;
    switch (pickerType) {
      case "gallery":

        /// GALLERY IMAGE PICKER
        pickedImage  = await _picker.pickImage(
            source: ImageSource.gallery);
        break;

      case "camera": // CAMERA CAPTURE CODE
        pickedImage  = await _picker.pickImage(
            source: ImageSource.camera);
        break;
    }
    if (pickedImage != null) {
      setState(() {
        debugPrint("SELECTED IMAGE PICK   $pickedImage");
        pImage = File(pickedImage!.path);
      });
    } else {
      print("You have not taken image");
    }

 }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(35),
            child: Column(children: [
              Center(
                // this button is used to open the image picker
                child: ElevatedButton(
                  onPressed:  () {
                      _settingModalBottomSheet(context, _image);
                    },
                  child: const Text('Select An Image'),
                ),
              ),
              const SizedBox(height: 35),
              // The picked image will be displayed here
              Container(
                alignment: Alignment.center,
                width: double.infinity,
                height: 300,
                color: Colors.grey[300],
                child: _image != null
                    ? Image.file(_image!, fit: BoxFit.cover)
                    : const Text('Please select an image'),
              ),
              Center(
                // this button is used to open the image picker
                child: ElevatedButton(
                  onPressed:  () {
                      _settingModalBottomSheet(context , _image2);
                    },
                  child: const Text('Select An Image'),
                ),
              ),
              const SizedBox(height: 35),
              // The picked image will be displayed here
              Container(
                alignment: Alignment.center,
                width: double.infinity,
                height: 300,
                color: Colors.grey[300],
                child: _image2!= null
                    ? Image.file(_image2!, fit: BoxFit.cover)
                    : const Text('Please select an image'),
              )
            ]),
          ),
        ));
  }

我还为重复变量创建了设置模式,所以我不必为每个变量复制相同的函数

void _settingModalBottomSheet(context , File? _imag) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext bc) {
          return Wrap(
            children: <Widget>[
              ListTile(
                  title: const Text('Gallery'),
                  onTap: () => {
                        _openImagePicker("gallery", _imag),
                        Navigator.pop(context),
                      }),
              ListTile(
                title: const Text('Camera'),
                onTap: () => {
                  _openImagePicker("camera", _imag),
                  Navigator.pop(context)
                },
              ),
              
            ],
          );
        });
  }

但当我运行该项目,似乎未来的功能没有返回图像文件的值,所以图像容器仍然空/空

irlmq6kh

irlmq6kh1#

var value=await _openImagePicker();

vsikbqxv

vsikbqxv2#

你得到了null,因为你设置了错误的变量。

  • 使用_openImagePicker()作为Future〈File?〉函数。
Future<File?> _openImagePicker(String pickerType) async { 
  XFile? pickedImage ;
  switch (pickerType) {
   case "gallery":
     /// GALLERY IMAGE PICKER
      pickedImage  = await _picker.pickImage(
          source: ImageSource.gallery);
        break;
      case "camera": // CAMERA CAPTURE CODE
        pickedImage  = await _picker.pickImage(
            source: ImageSource.camera);
        break;
    }
    if (pickedImage != null) {
      debugPrint("SELECTED IMAGE PICK   $pickedImage");
      final  tempImg = File(pickedImage!.path);
       return tempImg; 
    } else {
      print("You have not taken image");
    }
    return null;
 }

show dialog也是一个Future函数。你可以在对话框中调用_openImagePicker()。但是我更喜欢把它们分开。

Future<String?> _settingModalBottomSheet(context) {
    return showModalBottomSheet(
        context: context,
        builder: (BuildContext bc) {
          return Wrap(
            children: <Widget>[
              ListTile(
                  title: const Text('Gallery'),
                  onTap: () => {
                        //  this will close dialog and return "galery"
                        Navigator.pop(context,"galery"),
                      }),
              ListTile(
                title: const Text('Camera'),
                onTap: () => {
                 // this will close dialog and return "camera"
                  Navigator.pop(context,"camera"); 
                },
              ),
              
            ],
          );
        });
  }

现在使用它:

Center(
    // this button is used to open the image picker
    child: ElevatedButton(
       onPressed:  ()async {
         // call dialog and get value "camera" or "galery"
          final type = await  _settingModalBottomSheet(context);
             if(type != null){
               // call image pikcer
              final pickedFile = await _openImagePicker(type);
                if(pickedFile !=null){ 
                   // set here
                   setState(()
                       _image2 = pickedFile;
                     {});
                 }
              }
             
                  },
        child: const Text('Select An Image'),),
  ),

相关问题