0

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.

1 Answer 1

3

You can use remainder (%) to get back to the first index after a loop:

  void _incrementCounter() {
      setState(() {
        _counter = (_counter + 1) % nums.length;
      });
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.