gpt4 book ai didi

state - 如何从 Flutter 中的其他 StatefulWidget 设置/更新 StatefulWidget 的状态?

转载 作者:IT老高 更新时间:2023-10-28 12:29:10 34 4
gpt4 key购买 nike

  1. 例如,在下面的代码中,加号按钮可以工作并且能够更新文本,但减号按钮没有。
  2. 但如果我们按下 FloatingActionButton 则状态会被刷新。
  3. 减号按钮正在更改变量的值,但没有更新父窗口小部件的状态。

enter image description here

这里是代码.....

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

int number;

EdgeInsets globalMargin = const EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0);
TextStyle textStyle = const TextStyle(
fontSize: 100.0,
color: Colors.black,
);

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
void initState() {
super.initState();
number = number ?? 0;
}

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Column(
children: <Widget>[
new Text(
number.toString(),
style: textStyle,
),
new GridView.count(
crossAxisCount: 2,
shrinkWrap: true,
scrollDirection: Axis.vertical,
children: <Widget>[
new InkResponse(
child: new Container(
margin: globalMargin,
color: Colors.green,
child: new Center(
child: new Text(
"+",
style: textStyle,
),
)),
onTap: () {
setState(() {
number = number + 1;
});
},
),
new Sub(),
],
),
],
),
floatingActionButton: new FloatingActionButton(
onPressed: () {
setState(() {});
},
child: new Icon(Icons.update),
),
);
}
}

class Sub extends StatefulWidget {
@override
_SubState createState() => new _SubState();
}

class _SubState extends State<Sub> {
@override
Widget build(BuildContext context) {
return new InkResponse(
child: new Container(
margin: globalMargin,
color: Colors.red,
child: new Center(
child: new Text(
"-",
style: textStyle,
),
)),
onTap: () {
setState(() {
number = number - 1;
});
},
);
}
}

最佳答案

1.On Child Widget : 添加参数 Function 参数

class ChildWidget extends StatefulWidget {
final Function() notifyParent;
ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}

2.On Parent Widget : 创建一个Function让 child 回调

refresh() {
setState(() {});
}

3.On Parent Widget : 将 parentFunction 传递给 Child Widget

new ChildWidget( notifyParent: refresh );  

4.On Child Widget:调用父函数

  widget.notifyParent();

关于state - 如何从 Flutter 中的其他 StatefulWidget 设置/更新 StatefulWidget 的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48481590/

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