flutter function as parameter code example

Example 1: flutter use valuechanged function in function

class 1{
  //in the class where you need to use the callback declare as field
  Function(String value) onChanged,

  //then use the function as inChanged callback eventually adding code
  TextField(
    onChanged: (value){
        onChanged(value);
        state.didChange(value);
    },
  )
}

//in the other class pass the function like this
class 2{
	new 1({
    	...
        onChanged: (value) {
        	restaurant.name = value;
        },
        ...
    });
}

Example 2: dart callback function with parameter

class Obj {
	// <returnType> Function(<parameters>) fName;
	String Function(String, int, etc...) callbackName;
    
    // Call the callback function somewhere, eg constructor, textfield etc.
    Obj(this.callbackName);
}

main() {
	// Use the callback
	var myObj = Obj((String p1, int p2, etc...) {
		return "$p1$p2";
	});
}

Example 3: future as a parameter with async in flutter

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