0

How to pass variable declared to class widget. It is showing error "undefined name abcd". But I have already declared it. How to pass this variable abcd in Text widget. Code is attached. Thanks in advance.

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final String abcd = "abcd";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(
          children: [
            TextField(),
            OkButton(),
          ],
        ),
      ),
    );
  }
}

class OkButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FlatButton(
            onPressed: () {},
            child: Text("ok"),
          ),
          Text(abcd),
        ],
      ),
    );
  }
}
1
  • You need to add a constructor to pass a variable from a class to another one. Commented Jan 13, 2021 at 4:01

2 Answers 2

3

Add a constructor in the OkButton which accepts a String.

class OkButton extends StatelessWidget {
  OkButton({@required this.text});

  final String text;

  ...
    Text(text), // from Text(abcd),
  ...
}

Then, when you create OkButton, set the text property.

OkButton(text: abcd),
Sign up to request clarification or add additional context in comments.

1 Comment

yup, this is a good answer. but if you don't want it to mandatory just get rid of that @required. and if only 1 parameter I suggest not using a bracket, so it can be more compact like this OkButton(abcd),.
2

You can pass your value from one class to another by using Constructor

class _MyHomePageState extends State<MyHomePage> {
  final String abcd = "abcd";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(
          children: [
            TextField(),
            OkButton(abcd),
          ],
        ),
      ),
    );
  }
}

class OkButton extends StatelessWidget {
  final String abcd;
  OkButton(this.abcd);
  
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FlatButton(
            onPressed: () {},
            child: Text("ok"),
          ),
          Text(abcd),
        ],
      ),
    );
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.