Home > Enterprise >  How can i pass data from a child widget to a parent widget
How can i pass data from a child widget to a parent widget

Time:01-02

I have seen similar answers to my question, example is this How to pass data from child widget to its parent , but the data is passed through an onPressed event. How can i pass data from my child widget to the parent widget, without any onPressed or onTap event.

Code

  class ParentWidget extends StatelessWidget {
  String? passedData;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ChildWidget(),
          Text(passedData != null ? passedData! : 'No data passed'),
        ],
      ),
    );
  }
}

//How can i pass the title string to the ParentWidget as passedData String

class ChildWidget extends StatelessWidget {
  String title = 'Happy New Year';
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Container(
      child: Text(title),
    ));
  }
}

CodePudding user response:

You can use callback direct inside build method. To handle build error using setState need to wait a frame. I am using addPostFrameCallback.

class ParentWidget extends StatefulWidget {
  const ParentWidget({
    Key? key,
  }) : super(key: key);

  @override
  State<ParentWidget> createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  String? passedData;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ChildWidget(
            fallback: (p0) {
              WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
                setState(() {
                  passedData = p0;
                });
              });
            },
          ),
          Text(
            passedData == null ? 'No data passed' : passedData!,
          ),
        ],
      ),
    );
  }
}


class ChildWidget extends StatelessWidget {
  final String title = 'Happy New Year';
  final Function(String) fallback;

  const ChildWidget({
    Key? key,
    required this.fallback,
  }) : super(key: key);
  @override
  Widget build(BuildContext context) {
    fallback(title);
    return Center(
        child: Container(
      child: Text(title),
    ));
  }
}

  • Related