简体   繁体   中英

flutter variable is not passing in class widget

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM