0

Upon clicking, my app shows either yes, no, or maybe. How do I set the subsequent result strictly different from the previous one? For example, the current result is 'no', how do I randomize and make sure that the next result would ONLY either be 'yes' or 'maybe'?

enter image description here

This is the code

import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(
      MaterialApp(
        debugShowCheckedModeBanner: false,
        home: MyApp(),
      ),
    );

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            'Ask Me Anything',
            style: TextStyle(fontFamily: 'Lobster', fontSize: 25),
          ),
        ),
        body: picker(),
      ),
    );
  }
}

class picker extends StatefulWidget {
  @override
  _pickerState createState() => _pickerState();
}

class _pickerState extends State<picker> {
  List yourList = ["Yes", "No", "Maybe"];
  int randomIndex;

  _pickerState() {
    randomIndex = Random().nextInt(yourList.length);
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: TextButton(
        onPressed: () {
          setState(() {
            randomIndex = Random().nextInt(yourList.length);
            print("What's showing is '${yourList[randomIndex]}'");
          });
        },
        child: Stack(
          children: <Widget>[
            Center(child: Image.asset('images/blu.png')),
            Center(
              child: Text(
                yourList[randomIndex],
                style: TextStyle(fontSize: 40, fontFamily: 'Lobster'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

1 Answer 1

1

You could just do a while loop which keeps trying for a new answer as long as the answer is equal to the current answer:

_pickerState() {
oldIndex = randomIndex;
randomIndex = Random().nextInt(yourList.length);
while (oldIndex == randomIndex){
   randomIndex = Random().nextInt(yourList.length);
}

And then in your onPressed:

 setState(() {
        randomIndex = _pickerState();
        print("What's showing is '${yourList[randomIndex]}'");
      });
Sign up to request clarification or add additional context in comments.

1 Comment

How do I initialize oldIndex?

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.