Flutter / Dart: StatefulWidget - access class variable inside Widget

684

Attention: MyClass should be immutable.

1. If someString will never change

Keep it inside MyClass but define it as final.

class MyClass extends StatefulWidget {
  final String someString;

  const MyClass({Key key, this.someString = 'foo'}) : super(key: key);

  @override
  _MyClassState createState() => _MyClassState();
}

Then, inside the State, you can use it as widget.someString:

class _MyClassState extends State<MyClass> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('${widget.someString} is accessed here?!')),
    );
  }
}

2. If someString will change

It should be defined in the state.

class MyClass extends StatefulWidget {
  final String initialValue;

  const MyClass({Key key, this.initialValue = 'foo'}) : super(key: key);

  @override
  _MyClassState createState() => _MyClassState();
}

class _MyClassState extends State<MyClass> {
  String someString;

  @override
  void initState() {
    someString = widget.initialValue;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('$someString is accessed here?!')),
      body: Center(
        child: OutlinedButton(
          onPressed: () => setState(() => someString = 'NEW Value'),
          child: Text('Update value'),
        ),
      ),
    );
  }
}

enter image description here

Share:
684
BNetz
Author by

BNetz

Updated on December 12, 2022

Comments

  • BNetz
    BNetz over 1 year

    I declare a class variable for a StatefulWidget - in the code below it's someString. Is it possible to use this variable in the build(…)-method without declaring it as static?

    class MyClass extends StatefulWidget {
      String someString;
      MyClass() {
        this.someString = "foo";
      }
      @override
      _MyClassState createState() => _MyClassState();
    }
    
    class _MyClassState extends State<MyClass> {
      _MyClassState();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("someString - how to access it here?!"),
            // title: Text(someString), is not possible, obviously
          ),
        );
      }
    }
    

    Thanks in advance for help!

    • Raine Dale Holgado
      Raine Dale Holgado about 3 years
      you can directly access it like this Text(widget.someString);
  • BNetz
    BNetz about 3 years
    Thanks, Thierry, this is was extremely helpful! If someString will change - how is it possible to pass it to the State via the constructor?
  • Thierry
    Thierry about 3 years
    Is it changing within the MyClass widget or only from ancestors in the Widget Tree?
  • BNetz
    BNetz about 3 years
    In the MyClass widget.
  • Thierry
    Thierry about 3 years
    MyClass(initialValue: 'Azerty')