Flutter 父子组件 传值
发布日期:2021-10-10 05:31:04 浏览次数:29 分类:技术文章

本文共 2307 字,大约阅读时间需要 7 分钟。

首先是父组件

import 'package:flutter/material.dart';import 'package:testchuanzhi/Parent/ChildTwo.dart';import 'ChildOne.dart';// 传值class Parent extends StatefulWidget {
@override _ParentState createState() => _ParentState();}class _ParentState extends State
{
String data ='无'; String datatoParent ='来之父亲的问候'; void onDataChange(val) {
setState(() {
data = val; }); } @override Widget build(BuildContext context) {
return Container( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children:
[ ChildOne(), ChildTwo(datatoParent: datatoParent, callback: (val) => onDataChange(val)), Container( child: Text(data), ) ], ), ), ); }}

子组件

```kotlinimport 'package:flutter/material.dart';class ChildTwo extends StatefulWidget {
ChildTwo({
Key key, this.datatoParent, this.callback}) : super(key: key); final callback; String datatoParent; @override _ChildTwoState createState() => _ChildTwoState();}class _ChildTwoState extends State
{
String data ="来之父组件的问候"; void firedA() {
print("子组件里面促发了点击"); widget.callback('$inputTxt'); } String inputTxt; @override Widget build(BuildContext context) {
return Container( width: 100, margin: EdgeInsets.only(top: 3), child: Column( children:
[ Container( height: 20, width: 100, alignment: Alignment.center, margin: EdgeInsets.only(top: 3.0), decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(10.0)), child:Text(widget.datatoParent), ), RaisedButton( onPressed: firedA, child: new Text('to父组件'), ), TextField( decoration: const InputDecoration( hintText: '给父组件传值', contentPadding: const EdgeInsets.all(10.0), ), // 当监听的数值发生变化的时候 监听输入的数值 onChanged: (val) {
setState(() {
inputTxt = val; }); print(inputTxt); }), ], ), ); }}

转载地址:https://blog.csdn.net/qq_22049619/article/details/104432120 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Flutter 改变顶部状态栏颜色
下一篇:Flutter 自定义选项卡

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年03月31日 11时47分06秒