How to Emit the Data to Parent Widget In Flutter??

· 4 min read
How to Emit the Data to Parent Widget In Flutter
How to Emit the Data to Parent Widget In Flutter

Hello Flutterians !! Hope you guys are enjoying our article’s various articles like Image upload in flutter and How to Solve No Material Widget Found In Flutter. So this time we will move ahead with How to Emit the Data to Parent Widget In Flutter.

How to Emit the Data to Parent Widget In Flutter??

  • When the user passes abc from parent to child and you mutated the child value on press a button. As primitive types are pass by value in the dart, a change in the value of abc in a child will not change the value of parent abc. Refer to the below snippet.
void main() {
  String abc = "oldValue";
  changeIt(abc);
  print(abc); // oldValue
}

void changeIt(String abc) {
  abc = "newValue";
  print(abc); //newValue
}

Let’s assume the first one is wrong(for understanding purposes). Then changing the value of abc in a child will change the value of abc in the parent. But without calling that inside setState of a parent, the parent will not reflect the change. So if you change the code as below, it will change the button text alone on click.

new FlatButton(
    onPressed: () {
      setState(
        () {
          widget.abc = "RANDON TEXT";
        },
      );
    },
    child:
        new Text(widget.abc), // setting the text based on abc
    color: Colors.red,
  ),
  • Instead of using globalState which will be very difficult to maintain/debug as the app grows, I would recommend using callbacks. Please refer to the below code.
    void main() => runApp(new TestApp());
    
        class TestApp extends StatefulWidget {
          @override
          _TestState createState() => new _TestState();
        }
    
        class _TestState extends State<TestApp> {
          String abc = "bb";
    
          callback(newAbc) {
            setState(() {
              abc = newAbc;
            });
          }
    
          @override
          Widget build(BuildContext context) {
            var column = new Column(
              children: <Widget>[
                new Text("This is text $abc"),
                TestApp2(abc, callback)
              ],
            );
            return new MaterialApp(
              home: new Scaffold(
                body: new Padding(padding: EdgeInsets.all(30.0), child: column),
              ),
            );
          }
        }
    
        class TestApp2 extends StatefulWidget {
          String abc;
          Function(String) callback;
    
          TestApp2(this.abc, this.callback);
    
          @override
          _TestState2 createState() => new _TestState2();
        }
    
        class _TestState2 extends State<TestApp2> {
          @override
          Widget build(BuildContext context) {
            return new Container(
              width: 150.0,
              height: 30.0,
              margin: EdgeInsets.only(top: 50.0),
              child: new FlatButton(
                onPressed: () {
                  widget.callback("RANDON TEXT"); //call to parent
                },
                child: new Text(widget.abc),
                color: Colors.red,
              ),
            );
          }
        }

If you want to call the state of ParentScreen from another function/widget/class. Just follow this code

import 'package:showErrorMessage.dart';

class ParentScreen extends StatefulWidget {
  ParentScreen({Key key}) : super(key: key);

  @override
  _ParentScreenState createState() => _ParentScreenState();
}

class _ParentScreenState extends State<ParentScreen> {

   callback() {
    setState(() {});
  }
  
  @override
  Widget build(BuildContext context) {
    String message = "hello";
    return Container(
       child: showErrorMessage(message, callback);,
    );
  }
}

And here is the child widget/function/class

import 'package:flutter/material.dart';


    showErrorMessage(message, Function callback) {
      return Center(
      child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: [
      Text(
        message,
        style: TextStyle(color: Colors.white, fontSize: 16),
      ),
      GestureDetector(
          onTap: () {
            callback();  // ------ this will change/rebuild the state of its parent class
          },
          child: Icon(
            Icons.refresh,
            size: 30,
            color: Colors.white,
          )),
    ],
  ));
}

Conclusion:

Thanks for being with us on a Flutter Journey !!!

So in this article, we have been through How to Emit the Data to Parent Widget In Flutter.

Do not forget to drop us your valuable feedback to serve you better.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply