flutterdirectory-structure

example of how to separate sample project into separate files?


When you create a new project in Flutter v3.19, it creates a default app in /lib/main.dart

/lib/main.dart contains three classes:

class MyApp extends StatelessWidget

class MyHomePage extends StatefulWidget

class _MyHomePageState extends State<MyHomePage>

What is the best way to organize the file structure of the project so that those classes can be in separate folders/files? This will be for a small project.

Is there an example of what main.dart should look like so that it can import those classes? I couldn't find an example in the Flutter docs about this.

I tried to find an example of this, but couldn't. I would expect either simple docs from Flutter that explain this or the sample project to be setup with this in mind.

I found examples of folder structure, but nothing specifically for the sample project that comes with Flutter.


Solution

  • As simple format you can create two simple file cut and paste the code like following

    cut class MyApp extends StatelessWidget and create a file my_app.dart and paste it.

    cut

    class MyHomePage extends StatefulWidget
    
    class _MyHomePageState extends State<MyHomePage>
    

    together and create a file named home_page.dart and paste it.

    now you will find some error on the newly created file add import 'package:flutter/material.dart'; on both files. now you will find an error on main.dart so you have to import my_app.dart file and also import home_page in my_app Page.

    file Structure

    enter image description here

    main.dart

    enter image description here

    my_app.dart

    enter image description here

    home_page.dart enter image description here

    import file path will change according to project name and file structure