Dart:具有命名参数并执行函数的构造函数

发布于 2025-01-09 16:12:15 字数 725 浏览 0 评论 0原文

我想创建一个带有命名参数的类,它也执行一个函数。但是,我无法找到从构造函数调用函数的解决方案。是否有类似默认 init 函数的东西?

我的主要目标是在创建类后立即触发 init 函数,以显示 toast 通知。有谁知道我如何存档?

我正在使用的包: https://pub.dev/packages/fluttertoast

这是我的代码:

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

亲切的问候

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缱绻入梦 2025-01-16 16:12:15

你能为你的构造函数添加一个主体吗?

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

这会将以下内容打印到控制台:

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

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'.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文