directory

I will write a column on The nuggets about the basic process of Flutter mastery from the beginning to the relatively proficient. I will update my blog 1-2 times a week!

  • Flutter- Why do so many companies love Flutter

  • Learn about Flutter — Dart knowledge in 5 minutes

  • Learn about the Flutter project from here

  • Flutter started writing projects here

  • This makes it much easier to see the Flutter foundation and layout

  • How is rolling implemented in the Flutter project?

I will continue to provide quality content blog to you, the content currently covers objective-C, Swift, Flutter, small program development. Welcome to like blog and follow me, common progress ~~~

The problem

This series of articles is based on the latest release of Flutter, developed by Android Studio. This is the “engineering directory structure analysis” of Flutter from 0 to 1.

Set up the development environment for Flutter and create project first_FLUTTER. For the First_FLUTTER project, what is the project entry? What is the structure? Where do we put our code? With these problems, we solve them one by one!!

Functional structure and function

1.1 Functional Structure

View the created First_FLUTTER project as follows:

1.2 role

See the role of folder contents in the structure module below:

  • Dart_tool: a third-party library that dart relies on. Dart_tool is generated when a third-party library is downloaded. Package_config. json (package_config.json)

  • Idea file: Android Studio is developed by Google based on IDEA and is used to configure current projects.

  • Android file: Code related to the Android platform.

  • IOS file: iOS platform related code [can be run directly, including iOS real machine configuration also need to use this file]

  • Lib file: the main code we develop and write is here, functions and UI etc.

  • Test file: widget_test.dart- The test aspect of the component.

  • Gitignore: Do some Git ignoring.

  • Metadata: Make a record of the flutter version

  • Packages: addresses of dependent libraries

  • Firstflutter: Associated flutter configuration

  • Pubspec. lock: Writing of related dependencies

  • Pubspec. yaml: The writing of related dependency libraries

  • Readme: Project description

Ii Project Code

2.1 first_flutter code

When you’re done creating a new project, look at the main.dart file and you’ll see some neat code (with comments removed) as follows

Dart the entry to the application is the main function inside the main.dart file.

import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); }}Copy the code

2.2 First_FLUTTER operation effect

  • This is a counter case program, click on the bottom right corner of the + symbol, the number shown above will increase;

  • But when you first look at the code in Main.dart, you might find a lot of code that you don’t know how it was written.

As a beginner, my advice is to delete all the code inside the Flutter and create the code from zero. This way we can be very clear about the structure of the Flutter application. Start with:

Three advanced one

Before that, if you are not familiar with Dart, please read the previous article on Flutter for a first taste – Learn about Dart in 5 minutes

Any development starts with the ancestral Hello World, and now the requirement is to display a Hello World in the center of the interface

3.1 Code Implementation

import 'package:flutter/material.dart'; Main () {runApp(Text("Hello World ", textDirection: textdirection.ltr)); }Copy the code

3.2 The interface is as follows

3.3 Code query points

Of course, the above code already implements the interface to say Hello World

  • But it’s not centered and the font is a little bit small;
  • These problems, put later to solve, first understand the current a few lines of code;

Some of the above code is familiar, some is not clear:

  • For example, the Dart application entry is the main function, and the entry of Flutter is also the main function.

  • But what is the Material imported?

  • What about calling a runApp() function in main?

3.4 Code Analysis

3.4.1 track runApp and widgets

RunApp is a function provided by Flutter. This function is used to start a Flutter application. Check the source code of runApp and see the following code:

void runApp(Widget app) { ... Omit code}Copy the code

This function lets you pass in one thing: Widget?

1. There are many translations of widgets in China. 2. People who have done Android and iOS development like to translate it into controls; 3. People who have done Vue, React and other development like to translate it into components; 4. If we use Google, widgets translate to widgets; 5. There is no saying which translation is necessarily right or wrong, but I personally prefer widgets or components;Copy the code

What exactly is a Widget?

  • Learn about Flutter from the very beginning with one basic understanding: everything in Flutter is a Widget.

  • In iOS or Android development, there are many types of interfaces: Application, View Controller, Activity, View, Button, etc.

  • But in Flutter, these things are just different widgets;

  • That is, almost everything you see in your application is a Widget. Even for Padding, you need to use a Widget called Padding.

The runApp function lets us pass in a Widget:

  • But now there are no widgets, so what?

  • Import the Material library that Flutter has provided by default to use many of its built-in widgets;

3.4.2 Material Design Style [Import library, runApp global function in Material library]

What is material?

  • Material is a set of design style, or design language, design specification, etc. promoted by Google;

  • There are a lot of design rules, such as color, text layout, response animation and transitions, fill, etc.

  • There is a high degree of integration with Material style widgets in Flutter;

  • In our applications, we can use these widgets directly to create our applications (we’ll use more of them later);

Text widget analysis: Text() code analysis

class Text extends StatelessWidget {
  const Text(
    this.data, {
    Key key,
    this.style,
    this.strutStyle,
    this.textAlign,
    this.textDirection,
    this.locale,
    this.softWrap,
    this.overflow,
    this.textScaleFactor,
    this.maxLines,
    this.semanticsLabel,
    this.textWidthBasis,
  });
}
Copy the code
  • You can use the Text widget to display Text;

  • Find that the Text Widget inherits from the StatelessWidget and the StatelessWidget inherits from the Widget;

  • So you can pass the Text widget into the runApp function

  • There are a lot of attributes, but you’ve learned the Dart syntax, so only the this.data attribute must be passed in.

StatelessWidget

  • StatelessWidget inherits from Widget;

  • Its usage will be explained in more detail later;

    abstract class StatelessWidget extends Widget { // … Omit code}

Four advanced two

4.1 Optimization 1: Center

Finding that the current code is not the desired end result:

  • You may want the text to be centered and larger.

  • Center display: You need another Widget, Center;

  • Larger Text: You need to style the Text;

Modify the code as follows:

  • Wrap a Center widget around the Text widget, with Text as its child;

  • Also, we give the Text component a property: style, which corresponds to the TextStyle type;

Code implementation

import 'package:flutter/material.dart'; Void main() {// First step: Call runApp, flutter provides a global function 】 【 runApp function is the library in the header file, so you want to import package: flutter/material. The dart / / runApp need incoming Widget app, everything has its widgets 】 【 RunApp (Center(Child: Text("Hello World", textDirection: textDirection. LTR, style: TextStyle( fontSize: 30, color: Colors.orange, ), ), ) ); }Copy the code

The interface is as follows

4.2 Optimization 2: Improve the interface structure

Currently, we can display HelloWorld, but we find that the background at the bottom is black, and our page is not structured enough.

A normal App page should have a certain structure, such as a navigation bar, some background colors, etc

In development, there is no need to build such a structured interface from scratch. The Material library can be used directly to build some of the structure using some of the packaged components.

Code implementation

import 'package:flutter/material.dart'; Main () {// First step: Call runApp, flutter provides a global function 】 【 runApp function is the library in the header file, so you want to import package: flutter/material. The dart / / runApp need incoming Widget app, everything has its widgets 】 【 Widget is abstract and cannot be instantiated, so subclass runApp(MaterialApp(Home: Scaffold(appBar: appBar (title: Text(" first flutter project ")), body: TextDirection: textdirection. LTR, style: TextStyle(fontSize: 30, color: Colors.orange, ), ), ) , ) ) ); }Copy the code

The interface is as follows

Code analysis

Wrap a MaterialApp in the outermost layer

  • This means that the whole application will adopt some materialApp-style stuff, which is easy for us to design the application, and two of these properties are currently used;

  • Title: This is the title that will be displayed when opening the multitasking switch window on the Android system. (I don’t have to write it yet.)

  • Home: is the page that is displayed when the application is started, passing in a Scaffold;

What is scaffolding?

  • Scaffolding is used to build the basic structure of the page.

  • So a Scaffold object is passed to the Home property of the MaterialApp as a Widget to enable display. Scaffold also has some properties, such as appBar and body;

  • AppBar is used to design the navigation bar, passing in a title attribute;

  • The body is the content part of the page, passing in a Text Widget wrapped in the Center that was created earlier.

4.3 Optimization 3: The interface bears more elements

We can have more elements in the interface:

Code implementation

import 'package:flutter/material.dart'; Main () {// First step: Call runApp, flutter provides a global function 】 【 runApp function is the library in the header file, so you want to import package: flutter/material. The dart / / runApp need incoming Widget app, everything has its widgets 】 【 Widget is abstract and cannot be instantiated, so subclass runApp(MaterialApp(Home: Scaffold(appBar: appBar (title: Text(" first flutter project ")), body: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Checkbox( value: true, onChanged: (value) => print("Hello World")), textDirection: textdirection. LTR, style: TextStyle(fontSize: 20),)],),),),)); }Copy the code

The interface is as follows

See if there is a Debug flag in the upper right corner of the screenshot above, by adding a line of code to the MaterialApp:

debugShowCheckedModeBanner: false,
Copy the code

Look at the above code logic, do you feel like a lot of things in a method, and the code seems to be difficult to maintain and package, let’s refactor the code!!

5 project Reconstruction

5.1 Creating your own Widgets

Many people who learn about Flutter are discouraged by the nesting of Flutter. When code is nested too much, the structure is easily obscured.

The whole development process of Flutter is to form a tree of widgets, so nesting is normal.

But with so much nesting for such a simple program, what if the application were more complex?

  • We can encapsulate our code, encapsulate it in our own widgets, create our own widgets; How do you create your own widgets?

  • In Flutter development, you can inherit a StatelessWidget or StatefulWidget to create your own Widget class.

  • StatelessWidget: A Widget that has no state change and is usually just a display; StatefulWidget: A Widget whose state needs to be saved and whose state may change;

In the example above, we used the StatelessWidget to refactor our code, so let’s learn how to use the StatelessWidget to refactor our code.

Take a look at the StatefulWidget in a later example;

5.2 StatelessWidget

Statelesswidgets are typically widgets that have no State to maintain:

Take a look at the format for creating a StatelessWidget:

  • Make the Widget you create inherit from the StatelessWidget;

  • The StatelessWidget contains a method that must be overridden: the build method;

When is the build method executed?

  • When our StatelessWidget is first inserted into the Widget tree (that is, when it is first created);

  • When our parent Widget changes, the child Widget is rebuilt;

  • If our Widget relies on some data from the InheritedWidget, when the InheritedWidget data changes;

5.3 Refactoring the case code

We can now refactor our code using the StatelessWidget

Because our entire code is just some data presentation, no data changes, just use the StatelessWidget;

In addition, for better encapsulation, I split the code into two layers to make the code structure look clearer. (The specific splitting method is constantly reflected in the following cases. At present, two layers are split first.)

import 'package:flutter/material.dart'; // Use the arrow function when there is only one expression main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( DebugShowCheckedModeBanner: false, home: Scaffold (appBar: appBar (title: Text (" first Flutter project "),), the body: HomeContent(), ), ); } } class HomeContent extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Checkbox( value: true, onChanged: (value) => print("Hello World")), textDirection: textdirection. LTR, style: TextStyle(fontSize: 20), (], (), ( }}Copy the code

Through the above learning and understanding, I believe that the code of the First_FLUTTER project will have a clear understanding again.

Six Go Back

Here are some comments from the first_FLUTTER project code.

import 'package:flutter/material.dart'; Main () => runApp(MyApp()); Void main() {runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', // set theme: ThemeData(primarySwatch: colors. blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); }} /** * StatefulWidget: Divided into two classes * 1. Classes that integrate with StatefulWidget: 1. Have a mandatory method, as follows: createState() 2. Can receive data from the parent widget. */ class MyHomePage extends StatefulWidget {MyHomePage({Key Key, this.title}) : super(Key: Key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } // The next blog post will focus on StatefulWidget and StatelessWidget and state class _MyHomePageState extends State<MyHomePage> {int _counter = 0;  Void _incrementCounter() {setState() {_counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton(// Click onPressed: _incrementCounter, ToolTip: 'Increment', Child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); }}Copy the code

conclusion

This article describes in detail the overall framework and structure of the Flutter project as well as the description of the code. It also describes how to write the Flutter project from 0-1, as well as the knowledge points and skill points used in the project. You can write the above Demo manually. I believe that through the above examples and further progress, you can deepen your understanding and feeling of the Flutter project!!

In the next article we will cover the scrolling and presentation of the list of Flutter implementations.

Hope to help you, but also thank you for your praise and attention to my work, common progress, mutual encouragement!!