DEV Community

Adetoba ✨
Adetoba ✨

Posted on

Using Dart to create custom directories and files for your new Flutter project.

After my recent post on how to generate directories and files for your new flutter project in Golang, i got a comment on my twitter post to replicate this same implementation in dart. I agree with the comment since any flutter developer would already have dart installed on their system and won't necessarily need to setup Golang on their machine.

Tweet Screenshot

In this tutorial, we will learn how to generate custom directories and files for your new flutter project using dart.

Getting Started 👍

We will assume you already have flutter installed on your system so we'd skip the installation process and jump right into the implementation. Every Flutter SDK comes with a dart SDK which is automatically setup on your system.


Writing our codes 👨🏾‍💻

To start off, we will create a new dart file generator.dart which will contain all necessary functions for our program.

First, we import all necessary packages for our program

import 'dart.io';
Enter fullscreen mode Exit fullscreen mode
  • dart.io package allows us to manipulate files and directories in dart.
Map<String, List<String>> directories = {
  "features": [],
  "shared": [],
  "theme": [
    "colors.dart",
    "theme.dart",
    "styles.dart"
  ],
  "utils": [
    "utils.dart",
    "storage.dart",
    "dimensions.dart"
  ],
  "/features/auth": [],
  "/features/auth/view_models": []
};

Enter fullscreen mode Exit fullscreen mode
  • Create a key-value variable named directories of type Map<String, List<String>>. The key represents the name of the directory and the value represents the list of files to be created in the directory.
Future<Directory?> createDirectory(String path) async {
  try {
    final newDir = Directory(path);
    newDir.createSync(recursive: true);

    return newDir;
  } catch (e) {
    return null;
  }
}

Enter fullscreen mode Exit fullscreen mode
  • Create a function named createDirectory which takes in a string path as an argument. The path string represents the parent directory where we want to create all our custom directories.
  • Create a new Directory variable called newDir and specify the path.
  • newDir.createSync(recursive: true) function creates a new directory with the path you specified.
  • Use a try-catch block to handle exceptions. Return null if an exception occurs and return the newDir if the directory was successfully created.
Future<File?> createFile(String path, String fileName) async {
  try {
    final file = File("/$path/$fileName");
    final f = await file.create();
    return f;
  } catch (e) {
    return null;
  }
}

Enter fullscreen mode Exit fullscreen mode
  • Create a new function named createFile which takes two arguments. The first argument is the path where the file should be created and the second argument represents the file name.
  • Create a new File variable and specify the path and fileName.
  • Use await file.create() from the dart.io package to create a new file.

Now, let's create our main function

void main() {
  print("Please provide a path to the lib folder of your flutter project (e.g /Users/hash/Documents/test_app/lib): ");
  String? parentPath = stdin.readLineSync();

  if(parentPath == null) {
    print("You must provide a path");
    exit(0);
  }

  directories.forEach((directory, fileNames) async {
    String? fullPath = "/$parentPath/$directory";

    final dir = await createDirectory(fullPath);

    if (dir == null) {
      print("Failed to create directory: $directory");
    } else {
      print("=> $directory created");
    }

    for (String fileName in fileNames) {
      final file = await createFile(fullPath, fileName);

      if (file == null) {
        print("Failed to create file: $fileName");
      }

    }
  });
}

Enter fullscreen mode Exit fullscreen mode
  • The std.readLineSync() function is used to read an input from the command line. We store the input in a String variable called parentPath.
  • Check if the parentPath is not null and exit the app using exit(0) if the variable is null.
  • Use a forEach loop to iterate through the directories variable and create each directory using the createDirectory function you created earlier.
  • The createDirectory function takes an argument which represents the full path where the directory should be created. We combine the parentPath and the directory string to get the full path.
  • Create another for loop to iterate through each fileName in the directories map.
  • Use the createFile function we created earlier to create each file. Pass the full path and the filename as arguments to the function.

Next, create a new flutter project named test_app in your documents folder.

New flutter project

Now, we need to run our generator.dart file to generate our custom directories for our flutter project. Open up a terminal and make sure you're in the directory where your generator.dart file is stored then type dart run generator.dart

Terminal screenshot

You should see this screen if everything works as expected.

Complete project screenshot

Check the new flutter project you created to see if your files were generated successfully.

Conclusion 👏

We have learnt how to generate custom directories and files for our flutter project using dart. You can tweak this dart code and use it however necessary to create custom directories or files for your projects.

Top comments (1)

Collapse
 
pommedouze profile image
Olivier Revial

Nice demonstration, however I would tend to use Mason / Brickhub for such usecases as it offers the additional feature of setting templates files that can be customized to suit your team's specific needs 🙂
(note: I don't have anything to do with this package, I'm just a humble user)