Open In App

How to Shuffle a List using shuffle() in Flutter?

Last Updated : 04 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn how to develop an Android app in Flutter that shuffles the content of a list by calling shuffle( ). Here we will take the Benefits of the inbuilt shuffle() method from the dart:math library, which provides an easy approach to randomly arrange the items on a list.

Syntax:

List.shuffle(Random random)

The Random parameter allows you to provide a custom random number generator to control the shuffling behavior. If you erase the Random parameter, the default random number generator will be used. Here we are going to Build an Android app using Flutter in which after pressing a Button the content of the list will be shuffled randomly.

Required Tools

To build this app, you need the following items installed on your machine:

  1. Visual Studio Code / Android Studio
  2. Android Emulator / iOS Simulator / Physical Device device.
  3. Flutter Installed
  4. Flutter plugin for VS Code / Android Studio.

A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementations

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package 

First of all import material.dart file.

import 'package:flutter/material.dart';

Then import dart:math file. This library contains the shuffle() method.

import 'dart:math';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




void main() {
  runApp(ShuffleListApp());
}


Step 4: Create ShuffleListApp Class

In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.

Dart




class ShuffleListApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'GFG',
      theme: ThemeData(primarySwatch: Colors.green),
      home: ShuffleListScreen(),
    );
  }
}


Step 5: Create ShuffleListScreen Class

In this class, we are going to implement a scaffold to display our UI, and Here we are also applying the shuffle() method to a List, The UI contains a Button by pressing it the list items are shuffled randomly and our UI display the shuffled List items.

Dart




class ShuffleListScreen extends StatefulWidget {
  @override
  _ShuffleListScreenState createState() => _ShuffleListScreenState();
}
  
class _ShuffleListScreenState extends State<ShuffleListScreen> {
  List<String> items = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];
  
  void shuffleList() {
    setState(() {
      items.shuffle();
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GFG'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Original List',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 10),
            for (var item in items)
              Column(
                children: [
                  Text(
                    item,
                    style: TextStyle(fontSize: 20),
                  ),
                  SizedBox(height: 10),
                ],
              ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: shuffleList,
              child: Text('Shuffle List'),
            ),
          ],
        ),
      ),
    );
  }
}


Here is the full code to refer to the main.dart file

Dart




import 'dart:math';
import 'package:flutter/material.dart';
  
void main() {
  runApp(ShuffleListApp());
}
  
class ShuffleListApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'GFG',
      theme: ThemeData(primarySwatch: Colors.green),
      home: ShuffleListScreen(),
    );
  }
}
  
class ShuffleListScreen extends StatefulWidget {
  @override
  _ShuffleListScreenState createState() => _ShuffleListScreenState();
}
  
class _ShuffleListScreenState extends State<ShuffleListScreen> {
  List<String> items = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];
  
  void shuffleList() {
    setState(() {
      items.shuffle();
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GFG'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Original List',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 10),
            for (var item in items)
              Column(
                children: [
                  Text(
                    item,
                    style: TextStyle(fontSize: 20),
                  ),
                  SizedBox(height: 10),
                ],
              ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: shuffleList,
              child: Text('Shuffle List'),
            ),
          ],
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads