preface

Starting today, I will document the current development process of Flutter for Android. There is no time limit for the whole series of articles.

The overall structure

So let’s take a look at the structure of our app

This structure is relatively simple, this structure is based on playing Android site directory navigation extracted from several of the more commonly used. There will be a relatively detailed structure diagram for each section when writing it later.

Start page

Today is the first article in this series, taking a look at the startup page development process and how it works. The idea behind the launch page is to display the native splash screen first, and then use Flutter to create a transition page with a countdown function that jumps to the home page when the countdown is complete. The reason for this design is that, firstly, there is no proper way to eliminate the original flash screen page and directly jump to the transition page; secondly, some data used in the home page are requested in the transition page in advance for subsequent use. According to this idea, the implementation of the start page is mainly divided into the following three parts:

1. Modify the original splash screen

Please refer to my previous article about how to change the APP icon and startup page icon of Flutter. It describes how to change the Android and IOS startup page ICONS. This project also changes the splash screen in this way.

2. Create a transition page

The reason for designing this transition page is that I want to pre-request part of the interface data to be used by other subsequent pages through this page, so this page will have two main functions. First:The countdownThe second:Request some interface data. First take a look at the transition page, because to catch up with the schedule, so the transition page is relatively simple, first to see. The main function of this page is to countdown to the first page and download the first page rota data, using a Stack and a Stack layout. The core code is as follows:

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

/ / start page

class SpalashPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack(
      //Stack Stack layout
      alignment: AlignmentDirectional.topEnd,
      children: [
        Container(
          width: double.infinity,
          height: double.infinity,
          color: ColorsConfig.primaryColor,
          alignment: AlignmentDirectional.center,
          child: Text(
            "Technology connects the world.",
            style:
                TextStyle(color: Colors.white, decoration: TextDecoration.none),
          ),
        ),
        Positioned(
          child: CountDownWidget(),
          top: 30,
          right: 20,
          width: 60,
          height: 30,),); }}// Countdown skips components
class CountDownWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    returnCountDownWidgetState(); }}class CountDownWidgetState extends State<CountDownWidget> {
  // Start time of countdown
  int _countTime = 5;
  / / timer
  Timer _timer;
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          border: Border.all(width: 1, color: Colors.white)),
      child: GestureDetector(
        child: Text(
          "Skip",
          style: TextStyle(
            color: Colors.white,
            fontSize: 13,
            decoration: TextDecoration.none,
          ),
          textDirection: TextDirection.ltr,
        ),
        onTap: () {
          _timer.cancel();
          Navigator.pushNamed(context, "MainPage"); },),); }@override
  void initState() {
    // TODO: implement initState
    super.initState();
    _startCountDownTime();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer.cancel();
  }

// Countdown function
  void _startCountDownTime() {
    // Timer refresh frequency, refresh every 1s
    const dura = Duration(seconds: 1);
    var callback = (timer) => {
          setState(() {
            if (_countTime < 1) {
              // Cancel the countdown and jump to the home page
              _timer.cancel();
              Navigator.pushNamed(context, "MainPage");
            } else{ _countTime--; }})};// Timer instance_timer = Timer.periodic(dura, callback); }}Copy the code

3. Transition page network request

The UI construction of the transition page has been completed above. Next, we will first request the data used in the home page rotation chart on the transition page. The networking section uses DIO as our network request library. The whole process is divided into the following steps: 1. Import and configure the DIO library. Our bean class is generated by parsing JSON online. Before creating the bean class, we first request the interface data of the banner through Postman, and then generate the bean class online. The bean class corresponding to banner data is as follows: homebanner.dart

import 'dart:convert';

HomeBanner bannerFromJson(String str) => HomeBanner.fromJson(json.decode(str));

String bannerToJson(HomeBanner data) => json.encode(data.toJson());

class HomeBanner {
  HomeBanner({
    this.data,
    this.errorCode,
    this.errorMsg,
  });

  List<Datum> data;
  int errorCode;
  String errorMsg;

  factory HomeBanner.fromJson(Map<String.dynamic> json) => HomeBanner(
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
        errorCode: json["errorCode"],
        errorMsg: json["errorMsg"]);Map<String.dynamic> toJson() => {
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
        "errorCode": errorCode,
        "errorMsg": errorMsg,
      };
}

class Datum {
  Datum({
    this.desc,
    this.id,
    this.imagePath,
    this.isVisible,
    this.order,
    this.title,
    this.type,
    this.url,
  });

  String desc;
  int id;
  String imagePath;
  int isVisible;
  int order;
  String title;
  int type;
  String url;

  factory Datum.fromJson(Map<String.dynamic> json) => Datum(
        desc: json["desc"],
        id: json["id"],
        imagePath: json["imagePath"],
        isVisible: json["isVisible"],
        order: json["order"],
        title: json["title"],
        type: json["type"],
        url: json["url"]);Map<String.dynamic> toJson() => {
        "desc": desc,
        "id": id,
        "imagePath": imagePath,
        "isVisible": isVisible,
        "order": order,
        "title": title,
        "type": type,
        "url": url,
      };
}
Copy the code

Since the network request is a time-consuming operation, it can be executed in an asynchronous task. FutureBuilder is a useful and powerful asynchronous component of Flutter, where our web requests can be executed.

child: FutureBuilder(
            // Get requests banner data
            future: dio.get("/banner/json"),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                Response response = snapshot.data;
                // Parse the requested data
               
              }
              return Text(
                "Technology connects the world.", style: TextStyle( color: Colors.white, decoration: TextDecoration.none, ), ); },),Copy the code

4. Parse the banner data interface request back data are generally json format, above we created a HomeBanner class, this step requires us to return the interface json data parsing HomeBanner. Because Flutter does not support reflection, tools such as FastJson are not available, so we need to create our own bean classes as described above. But the parsing method that Flutter provides, json.decode(), converts json data into a Map, and then calls homeBanner.fromjson () to convert the json data into the desired bean class.

// Parse the requested data
Map bannerMap = json.decode(response.toString());
banner = HomeBanner.fromJson(bannerMap);
Copy the code

After these steps, our startup page is basically built, and we have requested some data in advance. These data will be provided to the home page banner rotation chart in the future. The next step is the process of building the main interface, which will be introduced in the next section.

conclusion

Record the coder’s life and be a happy coder.