Access child widget's variable in parent widget (Flutter with Dart)
Asked Answered
I

2

5

I have a button which when pressed opens a modal bottom sheet. The sheet has a form widget that takes few text fields and an image (from gallery/camera). For this image input, I have created another stateful widget which is called in the previous view (the modal sheet). Now, the image file received through user is set in a variable in the child stateful widget. My question is, how can I access this variable (a File object in child widget) inside the parent widget?

Please refer to the following code:

Bottom Sheet: (See comment where child widget is called.)

        context: _scaffoldKey.currentContext,
        builder: (BuildContext context) {
          return Scaffold(
              backgroundColor: Colors.white,
              appBar: AppBar(
                elevation: 0.0,
                automaticallyImplyLeading: false,
                backgroundColor: Colors.white,
                title: Center(
                  child: _formTitleWidget(),
                ),
              ),
              body: Container(
              height: MediaQuery.of(context).size.height* 0.5,
              margin: EdgeInsets.all(MediaQuery
                  .of(context)
                  .copyWith()
                  .size
                  .width * 0.05),
              child: Form(
                key: _addChildFormKey,
                child: SingleChildScrollView(
                  child: Container(
                    height: MediaQuery.of(context).size.height* 0.4,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        // Calling the child widget here - where 'image' variable is set
                        AddChildView(),
                        Container(
                          height: MediaQuery.of(context).size.height* 0.4,
                          width:  MediaQuery.of(context).size.width* 0.65,
                          child: Column(
                            children: [
                              _childNameInput(),
                              _childBirthDateInput(),
                              _childHeightInput(),
                              _childWeightInput(),
                              _addChildWithInfo()
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ),
            )
          );
        }```
Inelastic answered 29/9, 2019 at 22:21 Comment(1)
I would either pass a callback or work with Navigator.pop to send a result.Yawning
C
8

If you're not using a state management solution you will have to use a callback.

Create a variable in the parent. Create a method that takes in value and assigns it to the variable you just created.

Create a final Function and add it to the constructor in your child. Now when you instantiate the Child Widget in your Parent it will accept the method you just created.

Run the function in your child when appropriate.

class ParentWidget extends StatelessWidget {
  Image image;

  callBack(Image imageFromChild) {
    this.image = imageFromChild;
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

class ChildWidget extends StatelessWidget {
  final Function callBack;

  const ChildWidget({Key key, this.callBack}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FlatButton(
        child: Text('Press'),
        onPressed: () {
          var image = uploadImageMethod();
          callBack(image);
        },
      ),
    );
  }
}
Contraceptive answered 30/9, 2019 at 0:9 Comment(2)
Both the parent as well as child widgets are stateful widgets.Inelastic
When I said state management solution I meant app state solution not ephemeral state. for example bloc, mobx, redux, provider.Contraceptive
P
-1

class someChildWidget extends StatefulWidget {
  
  String someValue ;  // this is the value that should be accesible from a parent widget
  
  @override
  _someChildWidgetState createState() => _someChildWidgetState();
}

class _someChildWidgetState extends State<someChildWidget> {
  .
  .
  .
  
    metodInTheChild(String something) {
    setState(() {
       widget.someValue = something;
    
      });
   }
  }
  
  
  
  
class parentWidget extends StatefulWidget {
  @override
  _someChildWidgetState createState() => _someChildWidgetState(esRequerido);
}

class _parentWidgetState extends State<parentWidget> {
someChildWidget scw= someChildWidget();

    .
    .
    .
     metodInTheParent() {
      String value=swc.someValue; // now here is where you can access the value of the child widget
      
  }
Podite answered 26/6, 2020 at 16:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.