DEV Community

Cover image for Generate Random Password for users in your App — Building with Flutter

Posted on

Generate Random Password for users in your App — Building with Flutter

This image displays the topic of the tutorial

Security is one of the important features that are built into any mobile app where users have to create an account before interacting with the able and using it’s other features. From experience the process of creating an account password has been something people do without sometimes giving some deep thoughts. Some users create their own password while some prefer to get a suggestion of a strong password from the app.

The purpose of a password in an app is for user account security.

Let me take some lines to explain the concept of user account security.

User Account Security

User account security refers to the protection of user accounts from unauthorised access, misuse, and abuse. It is essential to ensure that only authorised users have access to sensitive information, systems, and applications. Here are some key concepts to understand when it comes to user account security:

  1. Passwords: A password is a secret combination of characters that a user must provide to access their account. Passwords should be strong, unique, and regularly changed to prevent unauthorised access. Users should avoid sharing their passwords with others and never use the same password across multiple accounts.
  2. Two-Factor Authentication (2FA): 2FA is a security mechanism that requires users to provide two different types of authentication factors before they can access their account. This typically involves a password and a secondary factor, such as a fingerprint or a one-time code sent via SMS or email.
  3. Access Controls: Access controls are mechanisms that limit who can access certain resources or information. Access controls can include things like user roles, permissions, and restrictions based on location or device.
  4. Monitoring: Monitoring is the process of tracking user activity to detect potential security threats. This can include monitoring login attempts, user behavior, and system logs to identify suspicious activity and potential security breaches.
  5. Education and Training: Education and training are crucial components of user account security. Users need to understand the risks of insecure practices such as weak passwords, phishing scams, and malware attacks. Organizations should provide regular training and awareness campaigns to ensure that users are aware of these risks and know how to avoid them.

Overall, user account security is an ongoing process that requires a combination of technical controls, policies, and user education. By implementing best practices and staying vigilant, organisations can help protect their users and sensitive information from potential security threats.

In the rest of this tutorial I’ll be looking at guiding the reader through a simple way of baking in app generated random characters which the user can use as their account password. This is tutorial would be relevant to you if you are building with Flutter (with Dart Programming Language).

Basic Requirements

  1. Knowledge of Dart Programming Language.
  2. Have Dart/Flutter installed using this video (this is a series, so follow through).
  3. A windows laptop of minimum 4GB RAM for running your Android studio or making use of DartPad.

I won't be writing on how to setup Dart/Flutter in your PC because this article would be too long to have that and the main tutorial of the article. So let's get down to writing a program that can help you generate random password for your users.

For first time test, The next thing to do is to create a new flutter project:

flutter create random-password
Enter fullscreen mode Exit fullscreen mode

This creates the well structure flutter project file where you have to locate your lib folder to write your first codes to test the solution on your own PC.

While solving some problems using Dart we need some libraries that help you build on some specific features of the language like dart:maths, dart:core etc.

In this program we will be importing the Dart library for maths operation:

import 'dart:math';
Enter fullscreen mode Exit fullscreen mode

This imports the Dart maths library: It helps you in using Mathematical constants and functions, plus a random number generator.

The next thing we have to do is to go under this block of code in your lib folder main.dart file and add a new function for your solution.

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

void main() {
  runApp(const MyApp());

// Add your own function here.
void testPassword() {


Enter fullscreen mode Exit fullscreen mode

This makes it possible for you to easily call your testPassword() function in the application root. This way in your code:

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
      home: const MyHomePage(title: 'Flutter Demo Home Page'),

Enter fullscreen mode Exit fullscreen mode

You call the testPassword() function within the build() this logs your program result to the debug console when you run your code in Debugging mode.

Let's write the core program for generating the random password, I'd do a breakdown of each line of the code.

We need to first declare the number of characters the password should be and this would be constant for all generated passwords.

const int passwordLength = 20;
Enter fullscreen mode Exit fullscreen mode

We then provide the program with some characters to choose from in generating the random password:

const String digits = 'StanruteTechnologies0123456789!@#\$%^&*()_-+={}[]|;:,.<>?';
Enter fullscreen mode Exit fullscreen mode

Now we go ahead and write the main code go generate the random password, here we make use of the different methods the dart:math library provides like Random():

Random random = Random();
  String password = '';
  for (int i = 0; i < passwordLength; i++) {
    password += digits[random.nextInt(digits.length)];

// To print your random password to the debug console.
Enter fullscreen mode Exit fullscreen mode

After this you can run the main.dart file to keep generating multiple random passwords.

Bring the whole code together we have something that looks like:

This is summarized code block for the article

This is written in a beginner friendly manner but any further questions can be directed to me here.

Thanks for Reading 💙

Top comments (0)