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
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:Then, you can display the correct string later like this:
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 witholdValue(itself) + "New String from your list"
, like this: