Evgenii Legotckoi
Evgenii LegotckoiJan. 7, 2019, 3:04 a.m.

Flutter - Tutorial 002. Creating a Splash Screen with the rounting to Home Screen

After Hello World on Flutter write an application with two screens:

  • SplashScreen - Application Input Screen
  • HomeScreen - Home screen application

Interestingly, Flutter has a navigation system for the windows (pages) of the application. This is somewhat similar to the route system in Django to determine which View to call.

In fact, in this application, we will need to call the MaterialApp widget, which accepts the routes route system, which will determine which windows to open. The first window will be SplashScreen , after two seconds it will have to open HomeScreen .


Project structure

SplashScreen project structure

I show only the necessary part of the project structure:

  • main.dart - file with the main function and the launch of MaterialApp
  • splash_screen.dart - initial application window
  • home_screen.dart - Home application window

main.dart

import 'package:flutter/material.dart';
import 'package:evileg/screens/Splash/splash_screen.dart';
import 'package:evileg/screens/Home/home_screen.dart';

// Application launch
void main() => runApp(MyApp());

// The main application widget
class MyApp extends StatelessWidget {

  // We form application routing
  final routes = <String, WidgetBuilder>{
    // The path that creates the Home Screen
    '/Home': (BuildContext context) => HomeScreen(title: 'EVILEG')
  };

  // Redefine widget instance construction method
  @override
  Widget build(BuildContext context) {
    // This will be an application with the support of Material Design.
    return MaterialApp(
      title: 'EVILEG',
      // in which there will be a Splash Screen indicating the next route
      home: SplashScreen(nextRoute: '/Home'),
      // passing routes to the application
      routes: routes,
    );
  }
}

splash_screen.dart

import 'dart:core';
import 'dart:async';
import 'package:flutter/material.dart';

// Inheriting from the state widget
// that is, a widget for changing the state of which is not required to recreate its instance
class SplashScreen extends StatefulWidget {
  // variable to store the route
  final String nextRoute;

  // the constructor, the constructor body is moved to the argument area,
  // that is, immediately the arguments are passed to the body of the constructor and set by internal variables
  // Dart allows it
  SplashScreen({this.nextRoute});

  // all same widgets should create their own state,
  // need to override this method
  @override
  State<StatefulWidget> createState() => _SplashScreenState();
}

// Create a widget state
class _SplashScreenState extends State<SplashScreen> {

  // State initialization
  @override
  void initState() {
    super.initState();
    // Create a timer to switch SplashScreen to HomeScreen after 2 seconds.
    Timer(
      Duration(seconds: 2),
      // To do this, use the static method of the navigator.
      // This is very similar to passing the lambda function to the std::function argument in C++.
      () { Navigator.of(context).pushReplacementNamed(widget.nextRoute); }
    );
  }

  // Widget creation
  @override
  Widget build(BuildContext context) {
    // And this is the layout of the widget,
    // a bit like QML although obviously not a JSON structure
    return Scaffold(
      backgroundColor: Colors.blue,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('EVILEG'),
            Text("Welcome to social network of programmers")
          ],
        ),
      ),
    );
  }

}

home_screen.dart

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

// The same widget as SplashScreen, just give it another title
class HomeScreen extends StatefulWidget {
  HomeScreen({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

// Creation a widget state
class _HomeScreenState extends State<HomeScreen> {

  // Unlike SplashScreen add AppBar
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Home page',),
          ],
        ),
      ),
    );
  }
}

Conclusion

As a result, we get the following two windows of the application.

SplashScreen

It is existing 2 seconds

SplashScreen

HomeScreen

Switches to it after SplashScreen

HomeScreen

Java vs Dart

Of course, I haven’t been engaged in the development for Android for a very long time, and even more so in Java. Surely everything has changed a lot and it is possible that for the better, but as far as I remember, Java paid less attention to creating a state, which sometimes caused some problems. Since this state was necessary to create, save, etc. Sometimes the application fell even when the screen was rotated. This caused very big problems and inconveniences.

In Dart, widgets are created with context passing when routing between windows. That is, as I understand it, the state of the application is no longer divided into different activations, but exists more monolithically. This may solve some of the problems that were in Java, but certainly can cause other problems that were not there. Find out about this in further articles. The most interesting is how it will end. In the end, at the moment I plan to try to write a mobile application for the site on Flutter / Dart.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

МШ
  • Oct. 22, 2022, 5:18 a.m.

Не работает, вставил код, поменял пути, но выдает ошибки

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 4:56 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 4:45 p.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 4:35 p.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 7:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 11:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 9:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 10:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks