Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

flutter
dart
communitycreator

How to create a simple splash screen in Flutter

Hammad Qayyum

What is a splash screen?

A splash screen is a screen that briefly opens whenever you open an application. A splash screen is also called the launch screen or startup screen and appears as soon as you click on the app icon to launch it. A splash screen usually appears for two to four seconds and then disappears, and the application home screen is launched. Below are some pictures of a splash screen.

How to create a splash screen in Flutter

We will use the Timer() function to create a splash screen in Flutter. First, we create a new Flutter application with the following command:

flutter create new_flutter_app

The application will be created and will have a main.dart file, where we add the following code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        
        
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePage() 
  }
}

We will create a stateful widget named SplashScreen and add the code for the splash screen in it. The splash screen can just have a simple logo or the name of the app.

First, we create a stateless widget in the main.dart file named homepage screen. Then, we add a simple code for the second screen and add some styling to it. After our widget for the second screen is ready, we just need to write code to connect it.

We will add the timer, which specifies how long the screen is displayed whenever it is launched. We add the timer in initState().

The following is the code to add a splash screen:

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    Timer(Duration(seconds: 3),
          ()=>Navigator.pushReplacement(context,MaterialPageRoute(builder:(context) => HomeScreen()));
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text("This is the splash screen")
    );
  }
}

The code below is added to the new homepage.dart file, which contains the screen displayed after the splash screen.

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title:Text("This is the secoind screen")),
      body: Text("Home page",textScaleFactor: 2,)
    );
  }
}

You can get the complete code here.

RELATED TAGS

flutter
dart
communitycreator
RELATED COURSES

View all Courses

Keep Exploring