smile just
smile just

Reputation: 13

How to update the Text in flutter from List

I have a Card widget.

Inside the Card widget I have Text widget and Raised Button widget.

I need to change the Text every time the Button is pressed, using an entry from a List which contains, for example, a list of names

void name=["Ali","mike","jack"]

On the first click, the Text will show "Ali", then the next click will show "mike", and so on.

How can I do this in Flutter?

Upvotes: 1

Views: 2609

Answers (2)

hifiaz
hifiaz

Reputation: 127

  1. first define your array as you mention
  2. define value default
  3. make looping on press

for detail code can refer to this code

class _MyHomePageState extends State<MyHomePage> {
  List data = ["One", "Two", "Three"];
  int i = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              data[i],
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            i = (i + 1) % data.length;
          });
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Upvotes: 1

Hannes Hulterg&#229;rd
Hannes Hulterg&#229;rd

Reputation: 1227

You can use setState to update the value. And to get the correct name in the list you just write name[i] where i is the index

Upvotes: 0

Related Questions