0

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

jamesdlin
  • 81,374
  • 13
  • 159
  • 204

3 Answers3

2

If what you mean to ask is if it's possible to call a function and pass arguments by reference instead of by value, then not exactly. Technically, Dart always uses pass-by-value (although I prefer calling it "pass-by-assignment").

If you want to simulate pass-by-reference, you could wrap your arguments in other objects to add a level of indirection:

class Reference<T> {
  T value;

  Reference(this.value);
}

void trimString(Reference<String> string) {
  string.value = string.value.trim();
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
1

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;
General Grievance
  • 4,555
  • 31
  • 31
  • 45
IonicFireBaseApp
  • 925
  • 3
  • 10
0

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
  }
blackkara
  • 4,900
  • 4
  • 28
  • 58