Skip to content

Creating New Screen

Follow these steps to create new screens in your Flutter project:

  1. [Optional but good to have] Make sure you have a screens folder in your lib folder

  2. Create a new file in the screens folder

  3. Name the file something and end with _screen.dart, for example login_screen.dart (feel free to rename it)

  4. Open the newly created Dart file

  5. Import material.dart:

    import 'package:flutter/material.dart';
    

  6. Create the class and the class name should be in PascalCase and extend either StatelessWidget or StatefulWidget

    TIP

    It is better to create as a StatelessWidget first and then later convert it into a StatefulWidget.

    class LoginScreen extends StatelessWidget {
    } // end of class
    
  7. In the class, always remember to add the routeName for the screen and the value will start with /:

    class LoginScreen extends StatelessWidget {
        static String routeName = '/login';
    }
    

  8. After creating the routeName, you will need to add the build() method and do not forget to add @override:

    class LoginScreen extends StatelessWidget {
        static String routeName = '/login';
    
        @override
        Widget build(BuildContext context) {
            return 
        }
    }
    

  9. In the build() method, normally a screen will have Scaffold as the base for the screen:

    NOTE

    If there is a tab in the screen, you will have DefaultTabController wrapped around the Scaffold first.

    class LoginScreen extends StatelessWidget {
        static String routeName = '/login';
    
        @override
        Widget build(BuildContext context) {
            return Scaffold(
                appBar: AppBar(), // This will be the AppBar
                body: Center(
                    child: Text('This is a sample screen'),
                ), // The content for the screen
            ); // Scaffold
        }
    }
    

  10. Save your changes

  11. Go to the main.dart file and "register" the route under the routes inside the MaterialApp properties:

    class MyApp extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
            return MaterialApp(
                home: MainScreen(),
                routes: {
                    LoginScreen.routeName: (context) => LoginScreen(),
                },
                debugShowCheckedModeBanner: false,
            );
        }
    }