gpt4 book ai didi

flutter - 使用其有状态小部件访问状态类的方法?

转载 作者:行者123 更新时间:2023-12-03 13:29:20 25 4
gpt4 key购买 nike

我在 state 类中有一个方法,但我需要使用它的小部件类引用在外部访问该方法,

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
},
),
]
),
);
}

我写了上面的代码只是为了演示这个问题。

最佳答案

我有一个技巧,但我不知道这是否是一种不好的做法。

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

关于flutter - 使用其有状态小部件访问状态类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56359361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com