sathish kumar
sathish kumar

Reputation: 1109

Flutter: How to pass parameter to Future async function

I have to pass parameter to Future async function from floatingbutton

My Codes like

FloatingActionButton(
                     onPressed: getImageFromCam,
                      tooltip: 'Pick Image',
                      child: Icon(Icons.add_a_photo),
                     ),

And

     Future getImageFromCam() async { // for camera
        var image = await ImagePicker.pickImage(source: ImageSource.camera);
        setState(() {
          _image = image;
        });
}

It is multiple button so i have to pass index to async function.

Can anyone please help to solve this.

Thanks in advance

Sathish

Upvotes: 1

Views: 8093

Answers (1)

Hugo Passos
Hugo Passos

Reputation: 8427

You cannot explicitly specify any argument when using a tear-off. Instead, you should manually define a closure:

FloatingActionButton(
  onPressed: () => getImageFromCam(index),
  tooltip: 'Pick Image',
  child: Icon(Icons.add_a_photo),
);

...

Future<void> getImageFromCam(int index) async {
  // Do whatever you want with `index`.
  final image = await ImagePicker.pickImage(source: ImageSource.camera);
  setState(() => _image = image);
}

Upvotes: 4

Related Questions