flutter中怎么子组件给父组件传值 代码
时间: 2023-09-08 18:14:43 浏览: 142
在 Flutter 中,父组件可以通过构造函数、方法、回调函数等方式将值传递给子组件。以下是一些示例代码:
1. 通过构造函数传值
父组件:
```
class ParentWidget extends StatelessWidget {
final String message;
ParentWidget({Key key, this.message}) : super(key: key);
@override
Widget build(BuildContext context) {
return ChildWidget(message: message);
}
}
```
子组件:
```
class ChildWidget extends StatelessWidget {
final String message;
ChildWidget({Key key, this.message}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(message);
}
}
```
2. 通过方法传值
父组件:
```
class ParentWidget extends StatefulWidget {
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
String message = 'Hello, world!';
void updateMessage(String newMessage) {
setState(() {
message = newMessage;
});
}
@override
Widget build(BuildContext context) {
return ChildWidget(updateMessage: updateMessage);
}
}
```
子组件:
```
class ChildWidget extends StatelessWidget {
final Function updateMessage;
ChildWidget({Key key, this.updateMessage}) : super(key: key);
@override
Widget build(BuildContext context) {
return RaisedButton(
child: Text('Click me'),
onPressed: () {
updateMessage('New message!');
},
);
}
}
```
3. 通过回调函数传值
父组件:
```
class ParentWidget extends StatefulWidget {
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
String message = 'Hello, world!';
void updateMessage(String newMessage) {
setState(() {
message = newMessage;
});
}
@override
Widget build(BuildContext context) {
return ChildWidget(onUpdateMessage: updateMessage);
}
}
```
子组件:
```
class ChildWidget extends StatelessWidget {
final Function(String) onUpdateMessage;
ChildWidget({Key key, this.onUpdateMessage}) : super(key: key);
@override
Widget build(BuildContext context) {
return RaisedButton(
child: Text('Click me'),
onPressed: () {
onUpdateMessage('New message!');
},
);
}
}
```
以上是三种常见的子组件给父组件传值的方式,在具体的实现中,应该根据具体情况选择最合适的方式。
阅读全文