skip to Main Content

I have a button, and am trying to have a counter-like functionality in my app, but instead of the counter increasing numerically by +1 when the button is pressed, I want a new string to appear. I am storing these Strings in a List function. I can’t use the ++ function on Strings, as that doesn’t work. But I cannot find another way to display my next string. Perhaps it’s more understandable this way: Let’s say my starting word is ‘Hello’. When I click my button, I want the next String contained in my List to appear. So the end result is that ‘Hello’ gets replaced by the next word contained in my List, which is ‘Hi’. Here is my code:

class MyHomePage extends StatefulWidget {
 const MyHomePage({super.key, required this.title});
 final String title;

   @override
  State<MyHomePage> createState() => _MyHomePageState();


 class _MyHomePageState extends State<MyHomePage> {
 List greetings = ['Hello', 'hi'];

 void _incrementCounter() {
setState(() {
  greetings++;
   });
 }

 @override
 Widget build(BuildContext context) {
    title: Text(widget.title),
  ),
  body: Center(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        const Text(
          'You have pushed the button this many times:',
        ),
        Text(
          '$greetings',
          style: Theme.of(context).textTheme.headlineMedium,
        ),
      ],
    ),
  ),
  floatingActionButton: FloatingActionButton(
    onPressed: _incrementCounter,
    tooltip: 'Increment',
    child: const Icon(Icons.add),
  ),
      );
         }
     }

I have tried all that I could find online, but I couldn’t find much information. Any help is greatly appreciated.

2

Answers


  1. Good question!
    It is correct that you cannot increment a list, but you can increment a list index and use that index to pick the correct list item.

    Let’s define a greetingsIndex variable and increment that instead of the list:

    List greetings = ['Hello', 'hi'];
    int greetingsIndex = 0;
    
    void _incrementCounter() {
        setState(() {
            greetingsIndex++;
        }
    });
    

    Then, you can display the correct string later like this:

    Text(
        '${greetings[greetingsIndex % greetings.length]}',
         style: Theme.of(context).textTheme.headlineMedium,
    )
    
    Login or Signup to reply.
  2. I hope I understand your question correctly.

    The String is a type that cannot increase(like a name), it’s not a number(like int), it just can change by reassigning its value;

    If you want to add a String to the Current String text that is displaying on the screen/widget you should define your changing string as a top-class variable and then reassign it with oldValue(itself) + "New String from your list", like this:

    class TestScreen extends StatefulWidget {
      const TestScreen({super.key});
    
      @override
      State<TestScreen> createState() => _TestScreenState();
    }
    
    class _TestScreenState extends State<TestScreen> {
      List<String> phrases = ['World!', 'Mike', 'Dad'];
      String greetings = 'Hello ';
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text(
                    'The Text Below Will Change After You Pressed The Button'),
                Text(
                  greetings,
                  style: Theme.of(context).textTheme.headlineMedium,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              setState(() {
                // this [0] after phrases indicates which element of phrases we want
                greetings = greetings + phrases[1];
              });
            },
            child: const Icon(Icons.add),
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search