[英]flutter, How to judge whether another widget is in the tree
實際上,我有一個父小部件,它的列中有一些子小部件。 像這樣
Container(
width: double.infinity,
color: Colors.white,
padding: EdgeInsets.fromLTRB(20.0, 50.0, 20.0, 0.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Title(),
SizedBox(height: 80.0,),
confirmLoginType(),
SizedBox(height: 10.0),
LoginButton(),
PolicyTips(
key: IndexGlobalKey.policyTipsKey,
updateState: receiveMessageUpdateState
),
Bottom()
],
),
),
在PolicyTips
中,我向它傳遞了一個密鑰,我想在LoginButton
中獲取密鑰,但是當我得到currentState
時它一直是null
。
LoginButton
class LoginButton extends StatefulWidget {
LoginButton({Key key}) : super(key: key);
@override
_LoginButtonState createState() => _LoginButtonState();
}
class _LoginButtonState extends State<LoginButton> {
@override
Widget build(BuildContext context) {
policyTipsKey = IndexGlobalKey.policyTipsKey.currentState;
return Container(
child: Text()
)
}
}
我能做些什么? 請幫幫我,謝謝。
IndexGlobalKey
代碼。class IndexGlobalKey {
static final GlobalKey<_PolicyTipsState> policyTipsKey = GlobalKey<_PolicyTipsState>();
static GlobalKey<_FormState> phoneLoginKey = GlobalKey<_FormState>();
static GlobalKey<_FormForIdCardLoginState> idCardLoginKey = GlobalKey<_FormForIdCardLoginState>();
}
_LoginButtonState
的構建方法在 PolicyTips 呈現之前和PolicyTips
實際設置之前IndexGlobalKey.policyTipsKey
。 原因是LoginButton
在列中的PolicyTips
之前。 這就是為什么當您從 _LoginButtonState 的構建中調用IndexGlobalKey.policyTipsKey.currentState
時會得到null
的_LoginButtonState
。
要解決此問題,您需要在使用它的地方調用IndexGlobalKey.policyTipsKey.state
。 例如,當您需要在點擊按鈕時獲取策略提示 state 時,只需在onPressed
回調中使用它:
class _LoginButtonState extends State<LoginButton> {
@override
Widget build(BuildContext context) {
// An example of your button
return TextButton(
onPressed: () {
final policyTipsState = IndexGlobalKey.policyTipsKey.currentState;
// Here you can use policyTipsState
},
child: Text('button'),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.