Home > Back-end >  Can I access a variable from the parent widget in a child widget in dart?
Can I access a variable from the parent widget in a child widget in dart?

Time:11-26

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),
        ),
      ),
    );
  }
}

CodePudding user response:

Try below code

    Text(widget.text),

CodePudding user response:

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),
        ),
      ),
    );
  }
}
  • Related