簡體   English   中英

如何從另一個 StatefulWidget class flutter 調用 StatefulWidget class 的方法?

[英]How to call method of StatefulWidget class from another StatefulWidget class flutter?

我正在開發一個 Flutter 應用程序項目,我需要在不同的 StatefulWidget class 上調用 StatefulWidget class 的一種方法。

請找到以下代碼:

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
    
    void clickEventTab(int index) {
    if (index == 0) {
      setState(() {
        ConstClass.currentScreen = HomeFragment();
        ConstClass.currentTab = 0;
      });
    } else if (index == 1) {
      setState(() {
        ConstClass.currentScreen = LoginFargment();
        ConstClass.currentTab = 1;
      });
    }
  }
}

現在我需要從下面提到的不同 class 調用這個clickEventTab(int index)方法:

class Profile extends StatefulWidget {
  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Container(
            height: double.infinity,
            width: double.infinity,
            GestureDetector(
                onTap: () {
                      // Need to call clickEventTab(1) from the HomeScreenNew class
                },
                child: Container(
                    height: 40.0,
                    width: 150.0,
                    color: Colors.red,
                    child: Center(
                      child: Text('Call HomeScreen'),
                    ),
                ),
            ),
          ),
        ),
    );
  }
}

您能否幫我解決如何從 Profile class 容器點擊事件中調用 HomeScreen class 的方法clickEventTab()

試試這個它對我有用;

class Profile extends StatefulWidget {
  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Container(
            height: double.infinity,
            width: double.infinity,
            GestureDetector(
                onTap: () {
                     HomeScreen().createState().clickEventTab(1);
                },
                child: Container(
                    height: 40.0,
                    width: 150.0,
                    color: Colors.red,
                    child: Center(
                      child: Text('Call HomeScreen'),
                    ),
                ),
            ),
          ),
        ),
    );
  }
}
 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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