Marek
Marek

Reputation: 219

Flutter list values

i've created a 2 lists of values. I mean, i have 2 lists with different values. Also i have a button with action to change bool value. If its true it will generate random value from cars List and false will generate random value from sportcars List. But i dont want to generate random value. I want to generate first value, then change to second, third, fourth,... and repeat this cycle

bool or = true;

child: Text(
            or ? cars[Random().nextInt(cars.length - 1)] : sportcars[Random().nextInt(sportcars.length - 1)],
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 20,
            ),
          ),

child: FloatingActionButton(
                heroTag: null,
                onPressed: () {
                  setState(() {
                    or = false;
                  });
                },

 child: FloatingActionButton(
                heroTag: null,
                onPressed: () {
                  setState(() {
                    or = true;
                  });
                },

Upvotes: 0

Views: 98

Answers (1)

Zaykahal
Zaykahal

Reputation: 92

You can create two variables equal to Zero, one for each list, and whenever you press the button you can view that specific list at that specific index. Then you can increment the variable after each view so that next time you can view the next element of the list, and when the variable reaches the end of the list, simple reinitialize it to 0 again with a simple if statement. That's how I would go about it based on what I understood from you question.

void main() {

 var list1 = [1,3,5,7];
 var var1 =0;

 var list2 = [2,4,6,8];
 var var2 =0;  

 bool value = false;

 if(value == false){
    print(list1[var1]);
    var1++;
 }else if(value == true){
    print(list2[var2]);
    var2++;
 }
}

this is what I have in mind, and each time you change the value between true and false you run this if condition, and it will also increment so you can view next element.

Upvotes: 1

Related Questions