[英]Flutter, how to call a function inside Stateful Widget from a returned Widget?
[英]Call a function inside Flutter Widget
我對 OOP 和 Flutter 很陌生。 我創建了以下小部件,並希望在另一個無狀態小部件中創建它時調用小部件 function。
我的計划是將小部件創建為子部件,然后使用定義的變量widgetState檢查它是否為真,如果是,它應該調用 void printSample() function。 條件檢查喊叫由小部件(InkWell)的 onTap 觸發。
帶有 Function 的小部件:
class WhiteCard extends StatelessWidget {
final widgetState = true;
final VoidCallback onTap;
final Color switchColor = Colors.red;
void printSample() {
print("Sample text");
}
const WhiteCard({
Key? key,
required this.onTap,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onTap,
child: Container(
width: 320,
height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18),
color: Colors.white,
),
child: Center(
child: ScreenController.isLargeScreen(context)
? Text("large")
: ScreenController.isMediumScreen(context)
? Text("medium")
: Text("small"),
),
),
);
}
}
調用 WhiteCard() 的小部件
class LargeScreen extends StatelessWidget {
const LargeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Expanded(
child: Container(
color: Colors.orangeAccent,
child: Center(
child: WhiteCard(
onTap: () {
CALL THE FUNCTION FROM WIDGET);
},
),
),
),
);
}
}
好吧,如果我正確理解了您的問題,那么您的 onTap 應該是這樣的:
onTap: () {
if (widgetState) {
printSample();
}
祝你好運,如有疑問請隨時回復
您還可以定義 function 以保留 object 清潔器的定義:
class LargeScreen extends StatelessWidget {
const LargeScreen({Key? key}) : super(key: key);
onTapFunction() {
// write he whatever you need to do when taping widget
}
@override
Widget build(BuildContext context) {
return Expanded(
child: Container(
color: Colors.orangeAccent,
child: Center(
child: WhiteCard(
onTap: onTapFunction,
),
),
),
);
}
}
因此,如果您需要從其他地方調用 onTapFunction,您可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.