我在状态类中有一个方法,但是我需要使用其窗口小部件类引用在外部访问该方法,
class TestFormState extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _testState();
}
}
class _testFormState extends State<TestFormState> {
int count = 1;
@override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.green,
child: Text("Count : $count"),
),
);
}
clickIncrease(){
setState(() { count += 1; });
}
}
,我需要在另一个窗口小部件中访问上述窗口小部件的clickIncrease,如下面的代码
class TutorialHome extends StatelessWidget {
TestFormState test;
@override
Widget build(BuildContext context) {
// Scaffold is a layout for the major Material Components.
return Scaffold(
body: Column(
children: <Widget>[
test = TestFormState(),
FlatButton(
child: Text("Increase"),
onPressed: (){
test.state.clickIncrease(); // This kind of thing I need to do
},
),
]
),
);
}
我写上面的代码只是为了说明问题。
答案 0 :(得分:0)
我有一个技巧,但我不知道这是否是一种不好的做法。
class TestFormState extends StatefulWidget {
_TestFormState _testFormState;
@override
State<StatefulWidget> createState() {
_testFormState = _TestFormState();
return _testFormState;
}
}
class _TestFormState extends State<TestFormState> {
int count = 1;
@override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.green,
child: Text("Count : $count"),
),
);
}
clickIncrease(){
setState(() { count += 1; });
}
}
现在,您可以在这里访问它:
class TutorialHome extends StatelessWidget {
TestFormState test;
@override
Widget build(BuildContext context) {
// Scaffold is a layout for the major Material Components.
return Scaffold(
body: Column(
children: <Widget>[
TextButton(
child: Text("Increase"),
onPressed: () {
test._testFormState
.clickIncrease(); // This is accessable
},
),
]
),
);
}
}
我建议看看ValueNotifier