Home > Software design >  How to pass a function by reference in flutter?
How to pass a function by reference in flutter?

Time:11-02

Is there any way to call a function by reference not by values in flutter.

CodePudding user response:

0

Very nice question indeed, in flutter Function is also first class object so you can pass them around any where.

you do it like

typedef ProfileFormSubmitCallback = void Function(
  String? photoUrl,
  String firstName,
  String lastName,
  String email,
);
then

you can reference your function like,

ProfileFormSubmitCallback myFunction;

CodePudding user response:

Not sure if this is what you mean, but lets say you have a Switch like this

Switch(
  value: false,
  onChanged: (value) {
    print(value);
  },
),

Then onChanged is a function. To use an existing function there instead like

void myFunction(bool value) {
  print(value);
}

you can simply do:

Switch(
  value: false,
  onChanged: myFunction,
),

CodePudding user response:

This is how a function is passed and used. Hope this is what you want

class ButtonPrimary extends StatelessWidget {
  final String text;
  final double? height;
  final double? width;
  final VoidCallback onPressed;
 

  const ButtonPrimary({
    Key? key,
    required this.onPressed,
    required this.text,
    this.height,
    this.width,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: height ?? 50,
      width: width ?? MediaQuery.of(context).size.width * .6,
      child: ElevatedButton(
        onPressed: onPressed,
        child: Widget(...),
      ),
    );
  }
}

And usage,

  ButtonPrimary(
   onPressed: onLoginPressed,
   text: 'Register',
   width: MediaQuery.of(context).size.width * .9,
  )

  ....

  void onLoginPressed() {
    // Do sth
  }
  • Related