Home Coding Truyền giá trị giữa parent-child widgets trong Flutter

Truyền giá trị giữa parent-child widgets trong Flutter

by Khanh Tran

Hôm nay tôi sẽ giới thiệu với các bạn một hướng dẫn cơ bản nhưng rất quan trọng. Đó là cách Truyền giá trị giữa parent-child widgets trong Flutter.

hình 1: pass value from child to parent

Tạo parent widget

Parent class là một StatefulWidget, để hiểu hơn về StatefulWidget vui lòng xem lại bài StatelessWidget và StatefulWidget trong Flutter.

Parent widget gồm một state data. Chúng ta sẽ thực hiện truyền data từ Parent sang ChildTwo và ngược lại.

import 'package:flutter/material.dart';
import 'package:testchuanzhi/Parent/ChildTwo.dart';

import 'ChildOne.dart';
// pass by value

class Parent extends StatefulWidget {
  @override
  _ParentState createState() => _ParentState();
}

class _ParentState extends State<Parent> {
  String data ='no';
  String datatoParent ='Greetings from the coming father';
  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),
              )
            ],
        ),
      ),
    );
  }
}

ChildTwo class

Child widget sẽ truyền dữ liệu lên parent widget thông qua một callback function:


```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 ="Greetings from the Father Component";
  void firedA() {
    print("A click was triggered in the subcomponent");
    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 parent component'),
          ),
          TextField(
              decoration: const InputDecoration(
                hintText: 'Pass value to parent component',
                contentPadding: const EdgeInsets.all(10.0),
              ),
              // When the monitored value changes, monitor the input value
              onChanged: (val) {
                setState(() {
                  inputTxt = val;
                });
                print(inputTxt);
              }),
        ],
      ),
    );
  }
}

Có bất kì thắc mắc nào, bạn hãy để lại comment ở dưới để có thể được giải đáp một cách nhanh chóng!

You may also like

Leave a Comment