Shaheen Zahedi
Shaheen Zahedi

Reputation: 1266

variable won't change Text dynamically in flutter

I have my application defined, and I pass counter variable as a constructor like below:

class AppThreePlusThree extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var game = new Game();
    var counter = 265;
    return new GameRedux(
      counter: counter,
      child: new MaterialApp(
        title: '3 + 3',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: new Scaffold(
     ...
     ...
     new Text('$counter'),
     ...

I modify the counter inside GameRedux, and I see variable changes, but it will not effect the Text in the UI, and it stocks on zero why?

Upvotes: 2

Views: 10949

Answers (1)

Blasanka
Blasanka

Reputation: 22427

You have to make your StatelessWidget widget to StatefulWidget because that is how layout rebuild when state of counter variable changed(using setState()). Your code should look like below,

class AppThreePlusThree extends StatefulWidget {
  _AppThreePlusThreeState createState() => _AppThreePlusThreeState ();
}

class _AppThreePlusThreeState extends State<AppThreePlusThree> {
  var counter = 265;
  var counter2 = 265;

  void changeVariableOnUI() {
    setState(() => counter2 = 22); 
  }

  @override
  Widget build(BuildContext context) {
    var game = new Game();
    // Inside the build method you cannot (no need) use setState but outside the build() to update a variable value on the UI have to use setState
    counter = 265; //I seriously doesnt have any idea how you are going to change or update your counter variable. something like this should work
    return new GameRedux(
      counter: counter,
      child: new MaterialApp(
        title: '3 + 3',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: new Scaffold(
     ...
     ...
     Text('$counter'),
     Text('$counter2'),
     InkWell(
       child: Text("Tap here"),
       onTap: changeVariableOnUI,
     ),
     ...

Upvotes: 7

Related Questions