[英]How to call method in child component from parent in flutter?
我有一個父組件和一個子組件。 一個例子如下:
class Parent extends StatefulWidget {
const Parent({Key? key}) : super(key: key);
@override
_ParentState createState() => _ParentState();
}
class _ParentState extends State<Parent> {
int stateVar = 1;
return Container(
child: Column(
children: [
FlatButton(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
onPressed: () {
setState() {
stateVar = stateVar + 1;
}
}
),
Child()
]
)
)
}
子組件是:
class Child extends StatefulWidget {
const Child({Key? key}) : super(key: key);
@override
_ChildState createState() => _ChildState();
}
class _ChildState extends State<Child> {
methodToCall() {
print("Method called");
}
return Container(
child: Text("Child text")
)
}
每當父組件中 state 變量stateVar
的值發生變化時,我想從父組件調用子組件內的方法methodToCall
。
在網上做了一些研究,我發現一種方法是使用博客中的GlobalKey
:https://stacksecrets.com/flutter/how-to-call-method-of-a-child-widget-from-parent-顫動中
但這行不通,因為這兩個組件位於不同的文件中,並且很難處理密鑰。 另一種方法是使用useEffect
但它不起作用。 有人可以幫忙嗎?
您可以讓您的Parent
class 擴展ChangeNotifier
並讓Children
class 收聽Parent
通知。
參見https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple#changenotifier
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.