skip to Main Content

Create 6 Distinctive Random Numbers using Flutter and Dart to make an app. Where these 6 different numbers don’t repeat themselves when they are randomize

Although I used this

import 'dart:math';

void main() {
  List<int> values = [];

  while (values.length < 6) {
    int randomValue = Random().nextInt(50);

    if (!values.contains(randomValue)) {
      values.add(randomValue);
    }
  }

  print('Randomized values: $values');
}

But I can’t use display it on the text widget in my app

2

Answers


  1. You can use Set instead of List.

    void main() {
      Set<int> values = {};
    
      while (values.length < 6) {
        int randomValue = Random().nextInt(50);
    
        if (!values.contains(randomValue)) {
          values.add(randomValue);
        }
      }
    
      print('Randomized values: $values');
    }
    

    This can take quite a time based on random generation.

    Login or Signup to reply.
  2. your code looks like pure Dart code.

    And your code is just fine to generate the 6 random numbers and put it into an array.

    If you have Flutter code around, you can just quickly do print the array in a Text() widget doing this:

    Text(values.toString())
    

    An entire class in Flutter using your same code could be:

    import 'dart:math';
    import 'package:flutter/material.dart';
    
    class YourClass extends StatelessWidget {
      const YourClass({super.key});
    
      @override
      Widget build(BuildContext context) {
        List<int> values = [];
        while (values.length < 6) {
          int randomValue = Random().nextInt(50);
          if (!values.contains(randomValue)) {
            values.add(randomValue);
          }
        }
        print('Randomized values: $values');
    
        return SafeArea(
          child: Scaffold(
              body: Text(values.toString())
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search