Search code examples
flutterdartmobilestatefulstatefulwidget

Stateful widget not rebuilding


In following code, there's a Greetings list, a Text widget and a 'Refresh' Elevated button. The entire app is a Stateful widget. I want the Text to change to the next greeting from the User list, when the user clicks the Refresh button.

However, when I run it, the Text doesn't change. All that happens is that the 'We have more greetings' text gets printed in the terminal.

Please help if you know how to resolve this!

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  var _greetingsIndex = 0;
  var _greetings = [
    "Hey, how are you!",
    "Trust you're fine, my friend!",
    "What's up!!!",
    "How are you doing!",
  ];

  void _refreshGreetings() {
    setState(() {
      _greetingsIndex = _greetingsIndex + 1;
    });
    if (_greetingsIndex < _greetings.length) {
      print('We have more greetings');
    } else {
      setState(() {
        _greetingsIndex = 0;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          appBar: AppBar(
            title: Text('Greetings app'),
          ),
          body: Column(
            children: [
              Text(_greetings[0]),
              ElevatedButton(
                  onPressed: _refreshGreetings, child: Text('Refresh'))
            ],
          ),
        ));
  }
}

Solution

  • You have a typo - you always show greeting with index 0. Instead of:

    body: Column(
                children: [
                  Text(_greetings[0]),
                  ElevatedButton(
                      onPressed: _refreshGreetings, child: Text('Refresh'))
                ],
              )
    

    Use

    body: Column(
                children: [
    
                  // this line needed fixing
                  Text(_greetings[_greetingsIndex]),
    
                  ElevatedButton(
                      onPressed: _refreshGreetings, child: Text('Refresh'))
                ],
              )