0

I want to access child widget variable value in parent widget whereas child widget is a const widget which does not allow me to use GlobalKey for const child widget.

My question is how can I access child widget without GlobalKey. Here is my code snippet:

class ParentWidget extends StatefulWidget {
   
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return ParentWidgetState();
  }
  
}

class ParentWidgetState extends State<ParentWidget>
{
@override
  Widget build(BuildContext context) {
  return Container(
  child: const LeftSidePanel(),);
  }
}

class LeftSidePanel extends StatefulWidget {
   
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return LeftPanelWidgetState();
  }
  const LeftSidePanel(
  );
}

class LeftSidePanelState extends State<LeftSidePanel>
{

}

Anyone there to answer my query please. Thanks

Dev94
  • 757
  • 6
  • 24

1 Answers1

0

In this example none of widgets have to be Statefull ( try to use as few statefull widgets as you can)

import 'package:flutter/material.dart';

class ParentWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: ChildWidget(
        getWidgetTextCallback: (someParameter) {
          print(someParameter);
          // here you can have the value from the Child widget use it wisely
        },
      ),
    );
  }
}

class ChildWidget extends StatelessWidget {
  final widgetText = 'widgetText';

  final Function(String) getWidgetTextCallback;

  const ChildWidget({required this.getWidgetTextCallback});
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(widgetText),
        ElevatedButton(
          onPressed:
              getWidgetTextCallback(widgetText),
          child: Text(widgetText),
        )
      ],
    );
  }
}
Jan-Stepien
  • 349
  • 2
  • 9
  • In my case both of these widgets (parent and child) are stateful widget. How can I pass this function as parameter with const widget. It doesn't allow me to define any parameter with const widget. If you could reproduce this code according to my code snippet provided above. – Dev94 Mar 14 '22 at 16:14