После Hello World на Flutter напишите приложение с двумя экранами:
- SplashScreen - Экран ввода приложения
- HomeScreen - приложение на главном экране
Интересно, что во Flutter есть система навигации по окнам (страницам) приложения. Это чем-то похоже на систему роутов в Django , чтобы определить, какой View вызывать.
На самом деле, в этом приложении нам нужно будет вызвать виджет MaterialApp, который принимает систему маршрутов routes , которая будет определять, какие окна открывать. Первым окном будет SplashScreen , через две секунды должно открыться HomeScreen .
Структура проекта
Я показываю только необходимую часть структуры проекта:
- main.dart - файл с основной функцией и запуском MaterialApp
- splash_screen.dart - начальное окно приложения
- home_screen.dart - Окно домашнего приложения
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',),
- ],
- ),
- ),
- );
- }
- }
Вывод
В результате получаем следующие два окна приложения.
SplashScreen
существует 2 секунды
HomeScreen
Переключается на него после SplashScreen
Java vs Dart
Конечно, я уже очень давно не занимаюсь разработкой под Android, а тем более на Java. Наверняка все сильно изменилось и возможно, что в лучшую сторону, но насколько я помню, в Java меньше внимания уделялось созданию состояния, что иногда вызывало некоторые проблемы. Так как это состояние нужно было создавать, сохранять и т.д. Иногда приложение падало даже при повороте экрана. Это доставляло очень большие проблемы и неудобства.
В Dart виджеты создаются с передачей контекста при маршрутизации между окнами. То есть, как я понимаю, состояние приложения уже не разделено на разные активации, а существует более монолитно. Это может решить некоторые проблемы, которые были в Java, но, безусловно, может вызвать другие проблемы, которых там не было. Узнайте об этом в следующих статьях. Самое интересное, чем это закончится. В итоге на данный момент планирую попробовать написать мобильное приложение для сайта на Flutter/Dart.
Не работает, вставил код, поменял пути, но выдает ошибки