Flutter: How can I make an button to show a random by me defined stateless Widget?

Viewed 835

I have an button, and when it gets pressed, an stateless Widget consisting of an Column with a few Text and an Image.Asset is shown. So now I have a few of these stateless Widgetswith different content. When I press the button, i want him now to show a ramdom one of these stateless Widgets, maybe an option for a specific order too. How do I do that?

Button and comamnd for showing the Widget at the moment:

body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                if (isShown == true) Zauberwuerfel(),
                SizedBox(
                  width: 150,
                  height: 100,
                ),
                Container(
                  padding: EdgeInsets.only(bottom: 60),
                  width: 230,
                  height: 130,
                  child: RaisedButton(
                      color: Colors.red,
                      child: Text('Skill', style: TextStyle(fontSize: 30)),
                      onPressed: () {
                        setState(() {
                          isShown = true;

One of those stateless Widgets:

class SkillJonglieren extends StatelessWidget {
  Widget build(BuildContext context) {
    return Column(children: <Widget>[
      Text(
        'Jonglieren',
        style: TextStyle(fontSize: 35),
      ),
      SizedBox(
        width: 20,
        height: 25,
      ),
      Image.asset('images/jonglieren.jpg', scale: 5),
      SizedBox(
        width: 20,
        height: 30,
      ),
      Row(mainAxisAlignment: MainAxisAlignment.center, children: <Text>[
        Text(
          'Schwierigkeit:',
          style: TextStyle(fontSize: 25),
        ),
        Text(
          ' Einfach',
          style: TextStyle(fontSize: 25, color: Colors.green),
3 Answers

Assign random numbers with the rand() function in dart:math to some variables. then use condition.

Use Random class to generate a random number.

  • The range of the random will always be equal to the number of StatelessWidget you have
  • You store a List which will keep your StatelessWidget
  • When the button is pressed, you get the random number, and then pick up the index based upon that random number generated

Assumptions: Let us assume you have 5 StatelessWidgets namely Widget1(), Widget2(), Widget3(), Widget4() and Widget5()

Let us quickly jump into the code

import 'dart:math';

// Each Widget is located at an index which is unique
int randomNumber;
List<Widget> _widgets = [Widget1(), Widget2(), Widget3(), Widget4(), Widget5()];

// generating random number
void _generateRandomNumber(){
   var random = new Random();

   // now the range works like 0 to n-1
   setState(() => randomNumber = random.nextInt(_widgets.length));
}


//Triggering the function when showing the item
RaisedButton(
   color: Colors.red,
   child: Text('Skill', style: TextStyle(fontSize: 30)),
   onPressed: () {
      //calling our method
      _generateRandomNumber();

      setState(() => isShown = true);
   }
)

Now showing the data finally

Column(
   mainAxisAlignment: MainAxisAlignment.spaceEvenly,
   children: <Widget>[
     if (isShown == true) _widgets[randomNumber]
     ....
   ]
)

First of all, you need to make your main widget a StateFulWidget since you want to toggle the isShown variable and make changes to the views. Then you need to make a list of Widgets(e.g., Widget1 and Widget2) in your main widget(which has the button in):

final List<Widget> widgets = [Widget1(), Widget2()];

To select one of these widgets randomly you can use:

(widgets..shuffle()).first

You need to select a new random widget in onPressed. To show the selected widget only when isShown is true, you can use a Visibility widget(the if method that you're using is ok, too). Finally set the child of this Visibility widget to the selected widget.

Full code:

final List<Widget> widgets = [Zauberwuerfel(), SkillJonglieren()];
var _isShown = false;
Widget _selectedWidget = Zauberwuerfel();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.grey,
        body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Visibility(
                  visible: _isShown,
                  child: _selectedWidget,
                ),
                SizedBox(
                  width: 150,
                  height: 100,
                ),
                Container(
                  padding: EdgeInsets.only(bottom: 60),
                  width: 230,
                  height: 130,
                ),
                RaisedButton(
                  color: Colors.red,
                  child: Text('Skill', style: TextStyle(fontSize: 30)),
                  onPressed: () {
                    setState(() {
                      _isShown = true;
                      _selectedWidget = (widgets..shuffle()).first;
                    });
                  },
                )
              ]),
        ));
  }
Related