![](/img/trans.png)
[英]How to call a function in a StatefulWidget from another StatefulWidget?
[英]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.