如何从另一个屏幕获取按钮点击的 onPressed 响应?
How to get the onPressed response of a Button click form another screen?
我在单独的文件中创建了一个按钮。尝试将 'onPressed' 作为函数传递,并通过构造函数从不同的屏幕获取点击响应。
按钮小部件
class FullWidthButton extends StatelessWidget {
const FullWidthButton({
Key? key,
required this.buttonText,
required this.onButtonPressed,
}) : super(key: key);
final String buttonText;
final Function onButtonPressed;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: FractionallySizedBox(
widthFactor: 1,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12),
textStyle: const TextStyle(fontSize: 24),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
),
onPressed: onButtonPressed,
child: Text(buttonText),
),
),
);
}
}
实施
FullWidthButton(
buttonText: 'Sign Up',
onButtonPressed: () => print('SignUp button is clicked!'),
)
错误
改为final Function onButtonPressed;
尝试final Function() onButtonPressed;
您已经传递了函数,但是 ElevatedButton 说他想要一个 Function(),而不是“class” Function
在您的 FullWidthButton
class 上试试这个 onPressed: ()=>onButtonPressed(),
。
你可以在我的answer
上看到原因
我在单独的文件中创建了一个按钮。尝试将 'onPressed' 作为函数传递,并通过构造函数从不同的屏幕获取点击响应。
按钮小部件
class FullWidthButton extends StatelessWidget {
const FullWidthButton({
Key? key,
required this.buttonText,
required this.onButtonPressed,
}) : super(key: key);
final String buttonText;
final Function onButtonPressed;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: FractionallySizedBox(
widthFactor: 1,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12),
textStyle: const TextStyle(fontSize: 24),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
),
onPressed: onButtonPressed,
child: Text(buttonText),
),
),
);
}
}
实施
FullWidthButton(
buttonText: 'Sign Up',
onButtonPressed: () => print('SignUp button is clicked!'),
)
错误
改为final Function onButtonPressed;
尝试final Function() onButtonPressed;
您已经传递了函数,但是 ElevatedButton 说他想要一个 Function(),而不是“class” Function
在您的 FullWidthButton
class 上试试这个 onPressed: ()=>onButtonPressed(),
。
你可以在我的answer