This is the second article in the series on Flutter. There are more about Flutter learning articles to come. If you like Flutter, please stay tuned.

Flutter is a cross-platform mobile development framework developed by Google using a programming language called FlutterDartIt is another exploration of cross-platform solutions by developers after React Native. By following its roots, it is essentially moving towards the unification of mobile terminals, reducing manpower, material resources and time! This is the common goal of developers and enterprises. In this article, we will explain the development process of Flutter application with a simple application.

The purpose of this article is to give users an intuitive understanding of the process of Flutter application creation, debugging, packaging, and installation. In your memory, learning a language starts with Hello World, and Flutter is no exception. Today, we start our first Flutter with a Hello Flutter application. The interface is very simple, mainly showing a counter that adds up as the user clicks.

Create a project

Before creating a project, you need to configure the development environment. If you haven’t already done this, please go to Build the development environment. If you have, please skip this.

  1. Select File>New Flutter Project
  2. Select Flutter Application as the Project type and click Next
  3. Enter the project name (e.g. flutter-app), store path, flutter SDK path selection, and then click Next
  4. Create the package name (lowercase, letters, numbers, underscores), click Finish,
  5. Waiting for Android Studio to create the project (the first time may take a while)

1. Project directory structure

  1. androidAndroid platform related code
  2. iosIOS platform related code
  3. buildThe directory generated by the compilation of the project, do not need to be concerned at this time (the output of the installation package compiled later is in this directory)
  4. libCross-platform code is also a major concern of the Flutter project
  5. testTest related code
  6. pubspec.yamlProject description file, equivalent to the NodeJs projectpackage.json, which contains the description of the project and the required dependent libraries

2.Flutter project entry file —lib/main.dart

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Welcome to Flutter'),
        ),theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
        body: new Center(
          child: new Text('Hello Flutter'),),),); ,); }}Copy the code

3. Run the above code, the effect is as follows:

Analysis of the

  • The default example creates a Material APP. Material is a standard visual design language for mobile and Web. Flutter provides a rich set of Material Widgets.
  • mainThe function (execution entry) uses (= >) symbol, which is shorthand for a single-line function or method in Dart.
  • The application inheritsStatelessWidgetThat means the application itself is also oneWidget.
  • ScaffoldIs a widget provided in the Material Library that provides a default navigation bar, title, and body property containing the widget tree on the main screen.
  • You can see from aboveWidgetThe main job of thebuild()Method to describe how to display itself against other lower-level widgets.
  • In this example, the Body widget tree contains a Center widget, which in turn contains a Text child widget. The Center Widget aligns its child widget tree to the Center of the screen.

Modify the project

Modify the project to make it the way we want it to be, adding a display text control and a clickable button to the screen, so we need to modify the entry file as follows: lib/main.dart.

1. Add oneStateful Widget

Here are a few concepts to understand:

  • Stateless widgets are immutable, which means their properties cannot be changed — all values are final.
  • State owned by Stateful Widgets can change during the widget life cycle. Implementing a stateful Widget requires at least two classes:
    1. A StatefulWidget class.
    2. A State class. The StatefulWidget class itself is immutable, but the State class is always present throughout the widget life cycle.

In this step, add a stateful widget–MyHomePage, which creates its State class _MyHomePageState. Here we add MyHomePage as a widget inside the existing stateless widget, MyApp.

  1. Create a State class and add it to the bottom of main.dart:

    class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is  the configurationfor the state. It holds the values (in this
      // case the title) provided by the parent (in this case the App widget) and
      // used by the build method of the State. Fields in a Widget subclass are
      // always marked "final".
    
      final String title;
    
      @override
      _MyHomePageState createState() => new _MyHomePageState();
    }
    Copy the code
  2. Add the _MyHomePageState class, which contains most of the application’s logic and state management code. This class keeps the number of user clicks on the screen, which increases as the user clicks and is displayed on the screen as follows:

    class _MyHomePageState extends State<MyHomePage> {
    	int _counter = 0;
    
      void _incrementCounter() {
        setState(() {
          _counter++;
        });
      }
    
      @override
      Widget build(BuildContext context) { 
        return new Scaffold(
          appBar: new AppBar(
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Text(
                  'You have pushed the button this many times:',
                ),
                new Text(
                  "$_counter",
                  style: Theme.of(context).textTheme.display1,
                ),
              ],
            ),
          ),
          floatingActionButton: new FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: new Icon(Icons.add),
          ), // This trailing comma makes auto-formatting nicer forbuild methods. ); }}Copy the code
  3. Replace the home argument inside the build method in MyApp with the newly defined MyHomePage widget:

    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Welcome to Flutter', theme: new ThemeData(primarySwatch: Colors. Green,// Change the theme style), home: new MyHomePage(title:'Flutter Demo Home Page')); }}Copy the code
  4. Restart the application. The behavior on the emulator should change as follows: show a counter and button, click the button, and the text count increases (with a change in style here).

  5. Modify interface code, style, save the interface number does not start from zero, which shows the difference between hot reload and restart, it simply changes the corresponding change, the State will continue to save.

To this we apply the transformation completed! The code is simple. The main thing we want to show the reader here is the process, components and simple configuration of creating a Flutter application.

Debug

Dart button on the top toolbar to start the application. You can make a breakpoint where you want to monitor the code as if it were native. This is the same as native. Another log output debugging method:

debugPrint("message info ...")
Copy the code

Here only a simple introduction, is not the focus of this chapter, here don’t do detailed analysis, readers more debugging method can according to need to look at https://flutter.io/debugging/ for further study.

Obtain the APK installation package

After running, testing, the application must be installed on the real machine, so you need to package apK and distribute it to users. Here we will examine how Flutter performs project packaging (Android).

  1. Check out the manifest configuration file androidmanifest.xml in the Android package. This is a template generation file that users can modify as needed;
  2. Build filebuild.gradle, here also can do some configuration, such as automatic signature configuration, resource compression, code obfuscation configuration and so on;
  3. Startup icon replacement;
  4. Compile the apk. Run the following commandflutter build apk, output the APK installation package tobuild/app/outputs/apk/release/app-release.apk;
  5. Install, execute in the root directoryflutter installYou are ready to install the APK.

conclusion

After reading the above steps, I think you will have in-depth thinking in the following aspects:

  1. Create a Flutter application from scratch.
  2. Write the Dart code.
  3. Use hot overloading to speed up development cycles.
  4. A stateful widget creation process and concept.
  5. How to package and debug an app

For IOS development, you can go to https://flutter.io/ios-release/ without going into details here. Well, this should be your first Flutter application. If you have a problem, you can leave a message and we can discuss it together. Thank you!