我在一個單獨的檔案中創建了一個按鈕。嘗試將“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!'),
)
錯誤

uj5u.com熱心網友回復:
而是final Function onButtonPressed;嘗試 final Function() onButtonPressed;
您已經傳遞了函式,但ElevatedButton說他想要一個 Function(),而不是“類”函式
uj5u.com熱心網友回復:
onPressed: ()=>onButtonPressed(),在你的FullWidthButton課堂上試試這個。你可以在我的回答中看到原因
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/480542.html
