美文网首页
Flutter 快速入门

Flutter 快速入门

作者: Jomeslu | 来源:发表于2018-06-26 12:13 被阅读157次

Flutter is a mobile App SDK by Google which helps in creating modern mobile apps for iOS and Android using a single(almost) code base. It’s a new entrant in the cross platform mobile application development and unlike other frameworks like React Native, it doesn’t use JavaScript as a Programming Language.

The programming language used by flutter is DART , which is similar to JavaScript in a way that it also runs a single threaded event queue. The biggest benefit of using Flutter is that it directly generates the ARM binaries which will execute directly on the native platform running it faster.

The installation instructions are present HERE. Both “Android Studio” and “IntelliJ IDEA Community” edition can be used to develop flutter applications.

Creating Flutter Apps — The Hierarchical Widgets

Everything within a Flutter application is a Widget in Flutter, from a simple “Text” to “Buttons” to “Screen Layouts”.

These widgets arrange in a hierarchical order to be displayed onto the screen. The widgets which can hold widgets inside it are called Container Widget. Most of the layout widgets are container widgets except for the widgets which does a minimal job like “Text Widget”

A bare minimal arrangement of widgets shall look like


1111.png

Hello Flutter : The first Flutter Code

With our first code, we’ll be displaying “Hello Flutter” on our Mobile App. We’ll use Container Widget called Directionality and Text Widget called Text to display the text onto the screen. Here is how the code looks like

import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext ctxt) {
    return new Directionality(
        textDirection: TextDirection.ltr,
        child: new Text("Hello Flutter")
    );
  }
}

As with many other programming languages, the main() function is the place where the execution starts. In the “Hello Flutter” code above, MyApp is a widget created by us which will build the screen layout.

In the code above, we create a “Container Widget” called “Directionality” which will have the sub widget called “Text” which shall display the text “Hello Flutter”. The widget hierarchy for this looks like


222.png

The text shall be displayed on the top of the screen, however, we can move the text at the center of the screen using a widget called “Center” which change the hierarchy as

333.png

And the code for the same looks like

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext ctxt) {
    return new Directionality(
        textDirection: TextDirection.ltr,
        child: new Center(                        // Changed Line
          child: new Text("Hello Flutter"),       // Changed Line
        )
    );
  }
}

Creating Material Designs

None of the applications we’ll create for real world will just have plain texts displayed on screen, instead an app shall bare minimum consists of Application Bar, Body, and Navigational Functionality.

In Flutter, we generally use MaterialApp for creating material design which allows us to use Scaffold which shall be used for creating Application Bar & Body. Here is how we create a bare minimum screen with MaterialApp and Body.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext ctxt) {
    return new MaterialApp(
      title: "MySampleApplication",
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text("Hello Flutter App"),
        ),
        body: new Center(
          child: new Text("Hello Flutter"),
        ),
      ),
    );
  }
}

And the widget hierarchy for the above shall look like

4444.png

Expanding Material Designs

In Material Design, the body can hold only one child widget which is not what we want. In general, the screen consists of multiple widgets.

To achieve the same, we need to use a widget as a child, which can hold array of widgets. There are multiple widgets in Flutter which can hold array of widgets as child, Row/Column is one of them. In the code above, we can add Row/Column to display multiple widgets which change the widgets hierarchy as

5555.png

And the code for the same looks like

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext ctxt) {
    return new MaterialApp(
      title: "MySampleApplication",
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text("Hello Flutter App"),
        ),
        body: new Center(
          child: new Row(
            children: <Widget>[
              new Text("Hello Flutter"),
              new Text("Hello Flutter - "),
            ],
        ),
       ),
      )
    );
  }
}

Passing Custom Parameters to the Widgets

The class MyApp is also a Widget created by our application. Just like any other builtin Widgets, we can also pass the parameters to the our widget. This is done providing the constructor on the class MyApp.

In the code below, our widget MyApp will be expecting a widget as input where we’ll provide the TextWidget as input

void main() => runApp(new MyApp(
  TextInput: new Text("Provided By Main"),
));
class MyApp extends StatelessWidget {
  MyApp({this.TextInput});
 final Widget TextInput;
  @override
  Widget build(BuildContext ctxt) {
    return new MaterialApp(
      title: "MySampleApplication",
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text("Hello Flutter App"),
        ),
        body: new Center(
          child: new Column(
            children: <Widget>[
              TextInput
            ],
          ),
        )
      ),
    );
  }
}

Stateless and Stateful Widgets

There are two types of widget we can create in flutter stateless and stateful. All the widgets we’ve created till now are stateless widgets.

Stateless Widgets and its limitations

A stateless widget can only be drawn only once when the Widget is loaded, which means we can’t redraw the Widget based on any events or user actions.

We can see this behaviour by having a Checkbox Widget. Checkbox Widget is a flutter Widget which has handler functions for Checkbox click, However, to display the checkbox with the click, we need to redraw the Widget which is only possible with hot reload or by reloading the widget itself

This doesn’t mean that stateless Widgets are not useful, it has its own usage in displaying static contents or the page which needs to be reloaded multiple times within an Application

Here is how the stateless widget with a checkbox shall look like

class MyApp extends StatelessWidget {
  MyApp({this.TextInput});
  final Widget TextInput;
  bool checkBoxValue = false;
  @override
  Widget build(BuildContext ctxt) {
    return new MaterialApp(
      title: "MySampleApplication",
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text("Hello Flutter App"),
        ),
        body: new Center(
          child: new Column(
            children: <Widget>[
              TextInput,
              new Checkbox(
                  value: checkBoxValue,
                  onChanged: (bool newValue){
                    checkBoxValue = newValue;
                  }
              )
            ],
          ),
        )
      ),
    );
  }
}

As you can see while running this code that nothing happens when we click the checkbox unless we reload the widgets

Statelful Widgets

Stateful Widgets overcomes the reloading deficiencies of the Stateless Widgets. A Stateful Widget can be loaded many times by calling setState(). This will trigger the build(BuildContext ctxt) to be called again.

The creation of Stateful Widgets are different than creating Stateless Widget as we need to create 2 classes, one is derived from Stateful Widget and another is derived from Generic State<>.

In every Stateful Widget we override the function createState(…) to create the instance of our stateful. Here is how the stateful widget code looks like

class MyApp extends StatefulWidget {
  MyApp({this.TextInput});
  final Widget TextInput;
  MyAppState createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
  bool checkBoxValue = false;
  @override
  Widget build(BuildContext ctxt) {
    return new MaterialApp(
      title: "MySampleApplication",
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text("Hello Flutter App"),
        ),
        body: new Center(
          child: new Column(
            children: <Widget>[
              widget.TextInput,
              new Checkbox(
                  value: checkBoxValue,
                  onChanged: (bool newValue){
                    setState(() {
                      checkBoxValue = newValue;
                    });
                  }
              )
            ],
          ),
        )
      ),
    );
  }
}

And the overall arrangement of the widgets hierarchy shall look like

6666.png

Adding AppBar Actions

No application is complete without providing the some AppBar actions, which sometimes include the well know three dots at the top right corner.

The AppBar constructor provides and options to add actions to create actionable items. Just like Row/Column it takes an array of Widgets which allows the creation of multiple actionable items. As an example, I’m adding couple of IconButton in the code

class MyApp extends StatefulWidget {
  MyApp({this.TextInput});
  final Widget TextInput;
  MyAppState createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
  bool checkBoxValue = false;
  String  actionText = "Default";
  @override
  Widget build(BuildContext ctxt) {
    return new MaterialApp(
      title: "MySampleApplication",
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text("Hello Flutter App"),
          actions: <Widget> [
              new IconButton (
                icon: new Icon(Icons.add_comment),
                onPressed: (){
                  setState(() {
                    actionText = "New Text";
                  });
                }
              ),
              new IconButton (
                  icon: new Icon(Icons.remove),
                  onPressed: (){
                    setState(() {
                      actionText = "Default";
                    });
                  }
              ),
            ]
        ),
        body: new Center(
          child: new Column(
            children: <Widget>[
              widget.TextInput,
              new Text(actionText),
              new Checkbox(
                  value: checkBoxValue,
                  onChanged: (bool newValue){
                    setState(() {
                      checkBoxValue = newValue;
                    });
                  }
              )
            ],
          ),
        )
      ),
    );
  }
}

The overall Widget hierarchy shall look like as depicted in the picture below. As earlier, any call to setState(…) shall redraw the complete MaterialApp, hence its manages to print the updated text on pressing the IconButtons

7777.png

Being Comfortable

We’ve covered enough in this section using which one can make very basic flutter apps. We’ll explore advanced functionalities in a separate blog.

干货推荐

Android博客周刊 :每周分享国内外热门技术博客以及优秀的类库、Google视频、面试经历。
最新源码汇总:每周分享新的开源代码,有效果图,更直观。请关注公众号,有惊喜。
开发工具汇总:包含了Android开发所需要的环境、在线小工具、开发神器、辅助工具、开发文档、学习教程。提供SDK 、AndroidSudio、 ADT、Gradle等等各个版本的下载。

相关文章

网友评论

      本文标题:Flutter 快速入门

      本文链接:https://www.haomeiwen.com/subject/sqipyftx.html