簡體   English   中英

flutter,如何判斷樹中是否有另一個小部件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM