![](/img/trans.png)
[英]how to Call method in one stateful widget from another stateful widget
[英]Call method of a widget from another widget
我剛剛開始顫抖,這是一個基本問題,但我無法解決。 我創建了一個有狀態小部件,我需要在單擊按鈕時調用setState()方法。 該按鈕不是此有狀態小部件的一部分。 該按鈕位於應用程序的頁腳中。
完整的應用代碼:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
build(BuildContext context) {
return new MaterialApp(
title: "My app title",
home: new Scaffold(
appBar: new AppBar(
title: new Text("My App"),
backgroundColor: Colors.amber,
),
body: new Container(
child: new Center(
child: new MyStateFullWidget(),
),
),
persistentFooterButtons: <Widget>[
new FlatButton(
onPressed: () {
// I need to call the update() of MyStateFullWidget/MyStateFullWidgetState class
},
child: new Text("Click Here"),
color: Colors.amber,
textColor: Colors.white,
),
],
));
}
}
class MyStateFullWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new MyStateFullWidgetState();
}
}
class MyStateFullWidgetState extends State<MyStateFullWidget> {
int count = 0;
@override
Widget build(BuildContext context) {
return new Text("Count: $count");
}
update() {
setState() {
count++;
}
}
}
我需要在單擊按鈕時調用setState()方法
您可能有一些選項(或替代方案)來實現最終結果(所有這些都有不同的權衡):
count
)提升為Button和Display Widget上方的Inherited Widget。 這可能是最簡單或最合適的。 dispatch
動作,通過StoreConnector
影響顯示小部件並重建)。 這可以被視為“提升”狀態的另一種方式。 但是,這需要一個全新的依賴項和大量的開銷給出你的簡單示例,但我想指出它。 可能還有其他解決方案,我沒有想到; 但請記住,反應式UI的目標是保持狀態簡單 。
因此,如果你有多個關注狀態的葉子小部件(想知道它,想要改變它),這可能意味着它屬於更高級別的組件(例如,應用程序級別的狀態,或者可能是某些其他常見的祖先 - 但兩者都可以使用Inherited Widget來阻止所有狀態的傳遞
您應該在State
中使用Scaffold
,而不是在StatelessWidget
中使用。 這是工作解決方案。
class MyApp extends StatelessWidget {
@override
build(BuildContext context) {
return MaterialApp(
title: "My app title",
home: MyStateFullWidget());
}
}
class MyStateFullWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MyStateFullWidgetState();
}
}
class MyStateFullWidgetState extends State<MyStateFullWidget> {
int count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("My App"),
backgroundColor: Colors.amber,
),
body: Container(
child: Center(
child:Text("Count: $count"),
),
),
persistentFooterButtons: <Widget>[
FlatButton(
onPressed: update,
child: Text("Click Here"),
color: Colors.amber,
textColor: Colors.white,
),
],
);
}
void update() {
setState(() {
count++;
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.