I have a simple question. I have a list of three integers. In my app, I have a floating action button. Each time when button is pressed the 'next' element of list is displayed. I have to reset to the first element once the looping is completed. I achieved this in a hard way;
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
List nums = [1, 2, 3];
void _incrementCounter() {
if (_counter <= 1) {
setState(() {
_counter++;
});
} else {
setState(() {
_counter = 0;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('${nums[_counter]}'),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
child: Icon(Icons.add),
),
);
}
}
I wish to know if there are some easier ways to achieve this. Thanks in advance for any help.