Evgenii Legotckoi
7 января 2019 г. 14:04

Flutter - Урок 002. Создание Splash Screen с переходом на Home Screen

После Hello World на Flutter напишите приложение с двумя экранами:

  • SplashScreen - Экран ввода приложения
  • HomeScreen - приложение на главном экране

Интересно, что во Flutter есть система навигации по окнам (страницам) приложения. Это чем-то похоже на систему роутов в Django , чтобы определить, какой View вызывать.

На самом деле, в этом приложении нам нужно будет вызвать виджет MaterialApp, который принимает систему маршрутов routes , которая будет определять, какие окна открывать. Первым окном будет SplashScreen , через две секунды должно открыться HomeScreen .


Структура проекта

SplashScreen project structure

Я показываю только необходимую часть структуры проекта:

  • main.dart - файл с основной функцией и запуском MaterialApp
  • splash_screen.dart - начальное окно приложения
  • home_screen.dart - Окно домашнего приложения

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. }

Вывод

В результате получаем следующие два окна приложения.

SplashScreen

существует 2 секунды

SplashScreen

HomeScreen

Переключается на него после SplashScreen

HomeScreen

Java vs Dart

Конечно, я уже очень давно не занимаюсь разработкой под Android, а тем более на Java. Наверняка все сильно изменилось и возможно, что в лучшую сторону, но насколько я помню, в Java меньше внимания уделялось созданию состояния, что иногда вызывало некоторые проблемы. Так как это состояние нужно было создавать, сохранять и т.д. Иногда приложение падало даже при повороте экрана. Это доставляло очень большие проблемы и неудобства.

В Dart виджеты создаются с передачей контекста при маршрутизации между окнами. То есть, как я понимаю, состояние приложения уже не разделено на разные активации, а существует более монолитно. Это может решить некоторые проблемы, которые были в Java, но, безусловно, может вызвать другие проблемы, которых там не было. Узнайте об этом в следующих статьях. Самое интересное, чем это закончится. В итоге на данный момент планирую попробовать написать мобильное приложение для сайта на Flutter/Dart.

Рекомендуемые статьи по этой тематике

По статье задано1вопрос(ов)

3

Вам это нравится? Поделитесь в социальных сетях!

МШ
  • 22 октября 2022 г. 15:18

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

Комментарии

Только авторизованные пользователи могут публиковать комментарии.
Пожалуйста, авторизуйтесь или зарегистрируйтесь