Home > Enterprise >  Dart: Constructor with named parameters and executing a function
Dart: Constructor with named parameters and executing a function

Time:02-24

I would like to create a class with named parameters which also executes a function. However, I am not able to find a soluiton to call a function from the constructor. Is there something like a default init function?

My main goal is to trigger the init function as soon as the class is being createtd in order to show a toast notification. Does anyone knows how I can archive that?

The package I am using: https://pub.dev/packages/fluttertoast

This is my code:

class CustomToast {
  CustomToast({required this.message});

  final String message;
  late FToast fToast;

  void init() {
    fToast = FToast();
    fToast.init(globalKey.currentState!.context);
    _showToast();
  }

  _showToast() {
    fToast.showToast(
      child: toast,
      gravity: ToastGravity.BOTTOM,
      toastDuration: const Duration(seconds: 1),
    );
  }

  Widget toast = Container(...);
}

Kind regards

CodePudding user response:

Could you add a body to your constructor?

class A {  
  final String a;
  
  A({this.a = 'default'}) {
    init();
  }
  
  void init() {
    print('New A has been created.');
  }
  
  String toString() => "A's value is '$a'.";
}

void main() {
  final myA = A(a: "My cool value");
  print(myA);
}

This prints the following to the console:

New A has been created.
A's value is 'My cool value'.
  • Related