【发布时间】:2022-01-18 17:18:28
【问题描述】:
在学习 Futter 的过程中,遇到了如何同时执行两个函数的问题。一个来自 Button 类中的构造函数的函数以及另一个在 Button 类中的函数。
这是一个示例代码:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
color: Colors.blueGrey,
child: Center(
child: Button(
whenButtonPressed: () {
print("Button pressed from outside the Button Class");
},
),
),
),
),
);
}
}
class Button extends StatelessWidget {
const Button({this.whenButtonPressed, Key? key}) : super(key: key);
final VoidCallback? whenButtonPressed;
@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: whenButtonPressed,
//print("Button pressed from inside the Button Class"); <- Execute this additionally.
backgroundColor: Colors.red,
);
}
}
我已经尝试将 onPressed 和其他打印语句放在大括号中。但随后只执行打印语句“从按钮类内部按下按钮”,而不执行 whenButtonPressed 函数。这种行为的原因是什么,我该如何正确编写?
class Button extends StatelessWidget {
const Button({this.whenButtonPressed, Key? key}) : super(key: key);
final VoidCallback? whenButtonPressed;
@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: (){ whenButtonPressed; // <-now this is not executed.
print("Button pressed from inside the Button Class");},
backgroundColor: Colors.red,
);
}
}
【问题讨论】:
-
为什么不使用 bloc 和 future 方法进行多个同步调用
-
尝试调用这个函数,比如
whenButtonPressed(),而不是whenButtonPressed。如果没有(),它只在分配函数时起作用,比如onPressed: whenButtonPressed。 -
是whenButtonPressed一个函数吗?
-
@彼得科尔泰。谢谢,这行得通。我使用您的解决方案为可能有相同问题的其他用户创建了我的问题的答案。
标签: flutter function class constructor