Search code examples
androidflutterdartmobile-application

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?


Solution

    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),
          ),
        );
      }
    }