我正在嘗試制作一個自定義ElevatedButton小部件,其建構式將接收以下兩個選項之一:
- 一個新頁面推送到
Navigator(我的自定義 StatefulWidget), - 或完全覆寫按鈕的回呼方法
onPressed。
我嘗試創建兩個單獨的建構式 - 一個用于每種可能性,但應該接收回呼方法的建構式似乎沒有得到它。當我除錯代碼時,我看到收到的物件是Closure.
我究竟做錯了什么?
import 'package:flutter/material.dart';
// ignore: must_be_immutable
class OrdinaryButton extends StatelessWidget {
final String? text;
Widget? goto;
late Function()? onPressed;
OrdinaryButton({this.text, this.goto});
OrdinaryButton.overrideOnPressed({this.text, required this.onPressed})
{
this.goto = null;
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
child: Text("$text"),
onPressed: () {
if(goto != null)
{
print("LOG: opening a new page...");
Navigator.push(context, MaterialPageRoute(builder: (context) => goto!));
}
else if(this.onPressed != null)
{
print("LOG: calling a custom function...");
this.onPressed; // This has the 'Closure' object instead of my callback.
}
},
);
}
}
uj5u.com熱心網友回復:
您在“onPressed”之后錯過了“!()”,您的代碼對我有用
hello() {
print("hello");
}
//Call this widget in my code
Column(
children: [
OrdinaryButton.overrideOnPressed(
onPressed: hello,
text: "Salut",
)
],
),
class OrdinaryButton extends StatelessWidget {
final String? text;
Widget? goto;
late Function()? onPressed;
OrdinaryButton({Key? key, this.text, this.goto}) : super(key: key);
OrdinaryButton.overrideOnPressed({this.text, required this.onPressed}) {
goto = null;
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
child: Text("$text"),
onPressed: () {
if (goto != null) {
print("LOG: opening a new page...");
Navigator.push(
context, MaterialPageRoute(builder: (context) => goto!));
} else if (onPressed != null) {
print("LOG: calling a custom function...");
onPressed!();
//you missed "!()" here after onPressed
}
},
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/518087.html
標籤:扑镖按钮打回来
上一篇:條件為真時禁用按鈕
