Flutter 父子组件 传值

首先是父组件

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<Parent> {
  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: <Widget>[
              ChildOne(),
              ChildTwo(datatoParent: datatoParent, callback: (val) => onDataChange(val)),
              Container(
                child: Text(data),
              )
            ],
        ),
      ),
    );
  }
}

子组件


```kotlin
import '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<ChildTwo> {
  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: <Widget>[
          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);
              }),
        ],
      ),
    );
  }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页