Search code examples
flutterdartinheritanceparent-childparent

Can I access a variable from the parent widget in a child widget in dart?


I am totally new to flutter/dart and not sure if my question is correct. In the following is a part of the code I am writing. Now I want to get that text variable from the SecondRoute widget and make a list of string using word from text variable(I do not know if I can do it with StatelessWidget).Now I can not get this "text" variable from the _SecondRouteState class and also I can not make a list from it in the SecondRoute widget. The text varibale is taking string from the user input and it is coming from the home screen.

class SecondRoute extends StatefulWidget {
  String text;
  SecondRoute({Key? key, required this.text}) : super(key: key);

  @override
  _SecondRouteState createState() => _SecondRouteState();

}

class _SecondRouteState extends State<SecondRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Route"),
      ),
      body: Center(
        child: Text(
          "hello world",
          // text,
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

Solution

  • You need to call with widget

    class SecondRoute extends StatefulWidget {
      String text;
      SecondRoute({Key? key, required this.text}) : super(key: key);
    
      @override
      _SecondRouteState createState() => _SecondRouteState();
    
    }
    
    class _SecondRouteState extends State<SecondRoute> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text("Second Route"),
          ),
          body: Center(
            child: Text(
              widget.text, // changes need
              style: TextStyle(fontSize: 24),
            ),
          ),
        );
      }
    }