skip to Main Content

I want to generate a random name without repeating the name

I tried a lot but did not get any result

Is there a way for me to do it

In fact, I’ve tried a lot on whether a variable is a number, The operation was completed successfully,

But I encountered difficulties in case the variable is of type name

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

class RandomName extends StatefulWidget {
static const id = 'RandomName';
const RandomName({super.key});

@override
State<RandomName> createState() => _RandomNameState();
}

class _RandomNameState extends State<RandomName> {
List<String> names = [];
Random random = Random();
TextEditingController nameController = TextEditingController();

This is the second part:

@override
Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Colors.grey[900],
  appBar: AppBar(),
  body: Column(
    children: [
      Expanded(
          child: ListView.builder(
              itemCount: names.length,
              itemBuilder: ((context, index) {
                return Dismissible(
                  key: UniqueKey(),
                  onDismissed: (direction) {
                    setState(() {
                      names.removeAt(index);
                    });
                  },
                  child: ListTile(
                    title: Text(names[index]),
                  ),
                );
              }))),
      Expanded(
        child: Padding(
          padding: EdgeInsets.all(20.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Text(
                "add new",
                style: TextStyle(
                    color: Colors.grey.shade500,
                    fontWeight: FontWeight.w600),
              ),
              Row(
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      autocorrect: false,
                      autofocus: true,
                      maxLines: 1,
                      cursorColor: Colors.grey.shade500,
                      cursorWidth: 1.5,
                      textInputAction: TextInputAction.done,
                      keyboardAppearance: Brightness.dark,
                      style: TextStyle(
                          fontSize: 20, color: Colors.grey.shade500),
                      textAlign: TextAlign.center,
                      keyboardType: TextInputType.name,
                      controller: nameController,
                      decoration: const InputDecoration(
                        border: InputBorder.none,
                        contentPadding:
                            EdgeInsets.only(top: 10, bottom: 10),
                        isDense: true,
                      ),
                    ),
                  ),
                  ElevatedButton(
                    child: Text('Add'),
                    onPressed: () {
                      addToList();
                      nameController.clear();
                    },
                  )
                ],
              ),
              Builder(
                  builder: (context) => ElevatedButton(
                      child: Text('Get Random Name'),
                      onPressed: () {
                        showAlertDialog(context);
                      }))
            ],
          ),
        ),
      ),
    ],
  ),
);
}

This is the third part:

The code is required to print four random names without repeating inside "Text"

Future<void> showAlertDialog(BuildContext context) {
return showDialog<void>(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        content: Container(
          margin: const EdgeInsets.all(8),
          padding: const EdgeInsets.all(5),
          width: MediaQuery.of(context).size.width / 1.3,
          height: MediaQuery.of(context).size.height / 3.5,
          color: Colors.grey.shade900,
          alignment: Alignment.center,
          child: Row(
            children: <Widget>[
              Text(
                names[random.nextInt(names.length)],
                textAlign: TextAlign.center,
                style: const TextStyle(fontSize: 15),
              ),
              Text(
                names[random.nextInt(names.length)],
                textAlign: TextAlign.center,
                style: const TextStyle(fontSize: 15),
              ),
              Text(
                names[random.nextInt(names.length)],
                textAlign: TextAlign.center,
                style: const TextStyle(fontSize: 15),
              ),
              Text(
                names[random.nextInt(names.length)],
                textAlign: TextAlign.center,
                style: const TextStyle(fontSize: 15),
              ),
            ],
          ),
        ),
        backgroundColor: Colors.grey.shade900,
      );
    });
    }

 void addToList() {
  if (nameController.text.isNotEmpty) {
   setState(() {
    names.add(nameController.text);
  });
  }
  }
  }

3

Answers


  1. Since you want to generate names when you click on the button, you effectively want to create a copy of the list and give it a shuffle inside the showAlertDialog() function.

    List<String> namesCopy = List.from(names)..shuffle();
    

    Replace Row() with Wrap() to prevent text overflowing to the right.

    Wrap(
      spacing: 8.0, // gap between adjacent chips
      runSpacing: 4.0, // gap between lines
    

    And finally, to prevent showing duplicates, generate a list of widgets that takes a count of 4 or the length of names, whichever is lower.

    min(4, namesCopy.length)
    

    The resulting showAlertDialog() function should look like this:

      Future<void> showAlertDialog(BuildContext context) {
        List<String> namesCopy = List.from(names)..shuffle();
        return showDialog<void>(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              content: Container(
                margin: const EdgeInsets.all(8),
                padding: const EdgeInsets.all(5),
                width: MediaQuery.of(context).size.width / 1.3,
                height: MediaQuery.of(context).size.height / 3.5,
                color: Colors.grey.shade900,
                alignment: Alignment.center,
                child: Wrap(
                  spacing: 8.0, // gap between adjacent chips
                  runSpacing: 4.0, // gap between lines
                  children: List<Widget>.generate(
                    min(4, namesCopy.length),
                    (index) => Text(
                      namesCopy[index],
                      textAlign: TextAlign.center,
                      style: const TextStyle(fontSize: 15),
                    ),
                  ),
                ),
              ),
              backgroundColor: Colors.grey.shade900,
            );
          },
        );
      }
    
    Login or Signup to reply.
  2. Check this one:

    import 'dart:math';
    import 'dart:async';
    
    List<String> names = [
      "Alice",
      "Bob",
      "Charlie",
      "David",
      "Eve",
      "Frank",
      "Gina",
      "Henry",
      "Ivy",
      "Joan",
    ];
    
    Set<String> usedNames = Set();
    Duration debounceDelay = Duration(milliseconds: 500);
    
    Timer? debounceTimer;
    
    Random random = Random();
    
    String getRandomName() {
      if (debounceTimer?.isActive ?? false) {
        return;
      }
    
      debounceTimer = Timer(debounceDelay, () {
        String name;
    
        do {
          name = names[random.nextInt(names.length)];
        } while (usedNames.contains(name));
    
        usedNames.add(name);
      });
    
      return name;
    }
    
    Login or Signup to reply.
  3. user this faker package to generate unique credentials name, email and a lots of other data

    import 'package:faker/faker.dart';
    
    main() {
      var faker = new Faker();
    
      faker.internet.email();
      // [email protected]
    
      faker.internet.ipv6Address();
      // 2450:a5bf:7855:8ce9:3693:58db:50bf:a105
    
      faker.internet.userName();
      // fiona-ward
    
      faker.person.name();
      // Fiona Ward
    
      faker.person.prefix();
      // Mrs.
    
      faker.person.suffix();
      // Sr.
      
      faker.lorem.sentence();
      // Nec nam aliquam sem et
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search