Evgenii Legotckoi
Jan. 7, 2019, 2:04 p.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

  1. import 'package:flutter/material.dart';
  2. import 'package:evileg/screens/Splash/splash_screen.dart';
  3. import 'package:evileg/screens/Home/home_screen.dart';
  4.  
  5. // Application launch
  6. void main() => runApp(MyApp());
  7.  
  8. // The main application widget
  9. class MyApp extends StatelessWidget {
  10.  
  11. // We form application routing
  12. final routes = <String, WidgetBuilder>{
  13. // The path that creates the Home Screen
  14. '/Home': (BuildContext context) => HomeScreen(title: 'EVILEG')
  15. };
  16.  
  17. // Redefine widget instance construction method
  18. @override
  19. Widget build(BuildContext context) {
  20. // This will be an application with the support of Material Design.
  21. return MaterialApp(
  22. title: 'EVILEG',
  23. // in which there will be a Splash Screen indicating the next route
  24. home: SplashScreen(nextRoute: '/Home'),
  25. // passing routes to the application
  26. routes: routes,
  27. );
  28. }
  29. }
  30.  

splash_screen.dart

  1. import 'dart:core';
  2. import 'dart:async';
  3. import 'package:flutter/material.dart';
  4.  
  5. // Inheriting from the state widget
  6. // that is, a widget for changing the state of which is not required to recreate its instance
  7. class SplashScreen extends StatefulWidget {
  8. // variable to store the route
  9. final String nextRoute;
  10.  
  11. // the constructor, the constructor body is moved to the argument area,
  12. // that is, immediately the arguments are passed to the body of the constructor and set by internal variables
  13. // Dart allows it
  14. SplashScreen({this.nextRoute});
  15.  
  16. // all same widgets should create their own state,
  17. // need to override this method
  18. @override
  19. State<StatefulWidget> createState() => _SplashScreenState();
  20. }
  21.  
  22. // Create a widget state
  23. class _SplashScreenState extends State<SplashScreen> {
  24.  
  25. // State initialization
  26. @override
  27. void initState() {
  28. super.initState();
  29. // Create a timer to switch SplashScreen to HomeScreen after 2 seconds.
  30. Timer(
  31. Duration(seconds: 2),
  32. // To do this, use the static method of the navigator.
  33. // This is very similar to passing the lambda function to the std::function argument in C++.
  34. () { Navigator.of(context).pushReplacementNamed(widget.nextRoute); }
  35. );
  36. }
  37.  
  38. // Widget creation
  39. @override
  40. Widget build(BuildContext context) {
  41. // And this is the layout of the widget,
  42. // a bit like QML although obviously not a JSON structure
  43. return Scaffold(
  44. backgroundColor: Colors.blue,
  45. body: Center(
  46. child: Column(
  47. mainAxisAlignment: MainAxisAlignment.center,
  48. children: <Widget>[
  49. Text('EVILEG'),
  50. Text("Welcome to social network of programmers")
  51. ],
  52. ),
  53. ),
  54. );
  55. }
  56.  
  57. }

home_screen.dart

  1. import 'dart:core';
  2. import 'package:flutter/material.dart';
  3.  
  4. // The same widget as SplashScreen, just give it another title
  5. class HomeScreen extends StatefulWidget {
  6. HomeScreen({Key key, this.title}) : super(key: key);
  7. final String title;
  8.  
  9. @override
  10. _HomeScreenState createState() => _HomeScreenState();
  11. }
  12.  
  13. // Creation a widget state
  14. class _HomeScreenState extends State<HomeScreen> {
  15.  
  16. // Unlike SplashScreen add AppBar
  17. @override
  18. Widget build(BuildContext context) {
  19. return Scaffold(
  20. appBar: AppBar(
  21. title: Text(widget.title),
  22. ),
  23. body: Center(
  24. child: Column(
  25. mainAxisAlignment: MainAxisAlignment.center,
  26. children: <Widget>[
  27. Text('Home page',),
  28. ],
  29. ),
  30. ),
  31. );
  32. }
  33. }

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.

Recommended articles on this topic

By article asked1question(s)

3

Do you like it? Share on social networks!

МШ
  • Oct. 22, 2022, 3:18 p.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html