gpt4 book ai didi

flutter - Flutter:外部小部件的setState

转载 作者:行者123 更新时间:2023-12-03 04:42:15 25 4
gpt4 key购买 nike

在默认的新flutter项目中,有floatActionButton。
我希望它在外部文件/小部件中,但在setState()时遇到问题
这可能吗?谢谢

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
_counter++;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

最佳答案

您可以将_incrementCounter方法向下传递给其他窗口小部件。
文件1:

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
_counter++;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: IncrementCounterButton(
incrementCounter: _incrementCounter,
),
);
}
}
文件2:
class IncrementCounterButton extends StatelessWidget {
final void Function() incrementCounter;

IncrementCounterButton({Key key, this.incrementCounter) : super(key: key);

@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
);
}
}

关于flutter - Flutter:外部小部件的setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62998357/

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