What is a flutter

  • Google’s cross-platform UI framework

Environment Setting (MAC Environment)

  • Flutter relies on the following command-line tools
bash, mkdir, rm, git, curl, unzip, which
Copy the code

Access to Flutter the SDK

  • Download the latest available flutter installation package from the Flutter website

  • After the installation package is downloaded, decompress it

Unzip/Specifies the decompression directory/flutter_macOS_v1.9.1 +hotfix.4- stablesCopy the code
  • After decompression, we will create a flutter directory under the decompressed directory. Get and remember the folder path, which we will use in the next step
Run the PWD command to view the directory path
/Users/XXXXX/development/flutter
Copy the code

Setting environment Variables

  • The purpose of setting the environment variable is so that we can run the FLUTTER command in any terminal session

  • To determine the Flutter SDK directory, step we extract to obtain the Flutter path/Users/XXXXX/development/Flutter

  • Open (or create)HOME refers to the path /Users/ user name XX/)

vim $HOME/.bash_profile
Copy the code
  • Add environment variables to the file
exportPUB_HOSTED_URL=https://pub.flutter-io.cn // This parameter is required for domestic usersexportFLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn // This parameter is required for domestic usersexport PATH=/Users/XXXXX/development/flutter/bin:$PATH
Copy the code
  • Finally, we execute the created.bash_profile file
source $HOME/.bash_profile Note: if you are using ZSH, ~/.bash_profile will not be loaded when the terminal starts. The solution is to modify ~/.zshrc to add:source ~/.bash_profile
Copy the code
  • Flutter dev site

Execute the Flutter Docter to check the local software environment. If the flutter docter is not installed, install it as prompted

flutter doctor
Copy the code

Manually Upgrade the Flutter

  • The upgrade of Flutter version is very fast. The SDK downloaded earlier is stable by default. How to manually upgrade flutter version? All that is required is the following flutter command
flutter upgrade
Copy the code

The Dart grammar

  • Dart is an object-oriented programming language. Each Object is an instance of a class. All classes inherit from Object. If you are familiar with Java, the language is easy to learn. First, familiarize yourself with the Dart syntax

The Dart variable

  • Name is a String and number is an int. The type cannot be changed. Uninitialized variables get a default value of null.
var name = 'maoqitian';
var number = 1;
Copy the code

The Dart constants

  • Final and const declarations are constants. A final variable can only be assigned once. You can omit the variable type by declaring a List array that holds WordPair values
final List _suggestions = new List<WordPair>();

final _suggestions = <WordPair>[];

Copy the code
  • The const keyword is not only used to define constants; it can also be used to create immutable values
Final _biggerFont = const TextStyle(fontSize: 18.0)Copy the code

Final and const

  • Const values are determined at compile time, and final values are not determined until run time

Dart function method

  • Dart is a true object-oriented language, methods are objects and its type is Function. This means that methods can be assigned to variables or treated as arguments to other methods.
Bool isNoble(int atomicNumber) {bool isNoble(int atomicNumber) {return _nobleGases[atomicNumber] != null;
}
//转换如下可以忽略类型定义
isNoble(atomicNumber) {
  return_nobleGases[atomicNumber] ! = null; } // only one expression method, you can choose to use the abbreviation syntax to define // => expr syntax is {returnexpr; } bool isNoble(int atomicNumber) => _nobleGases[atomicNumber]! = null;Copy the code

Dart method parameters

  • Methods can define two types of parameters: required and optional. The required parameters come before the parameter list, followed by the optional parameters. The required parameters are nothing to talk about. Let’s look at optional parameters. Optional parameters can be self-named or based on optional location, but they cannot be used together as optional parameters.

Optional named parameter

  • When calling an optional named parameter method, you can specify the parameter value by using the paramName: value form (key:value)
// Call the method playGames playGames(bold:true, hidden: false); PlayGames ({bool bold, bool hidden}) {//... }Copy the code

Optional position parameter

  • The parameters modified with [] in the method argument list are optional positional parameters
// Define optional position argument method String playGames (String from, String MSG, [String sports]) {var result ='$from suggest $msg';
  if(sports ! = null) { result ='$result playing $sports together';
  }
  returnresult; } // playGames('Bob'.'Howdy'); Bob suggest Howdy // playGames('I'.'Xiao Ming'.'basketball'); // return I suggest Xiao Ming playing basketball together.Copy the code

Dart method parameter default value

  • When defining methods, you can use = to define default values for optional arguments. The default value can only be compile-time constants. If no default value is provided, the default value is null
// Define the optional positional argument method String playGames (String from, String MSG, [String sports =)'football']) {
  var result = '$from suggest $msg';
  if(sports ! = null) { result ='$result playing $sports together';
  }
  return result;
}

playGames('I'.'Xiao Ming'); // Return I suggest Xiao Ming playing football together.Copy the code

The main() function

  • Every application needs a top-level main() entry method to execute
Void main() => runApp(MyApp()); // Can be converted to voidmain(){
    runApp(MyApp());
}
Copy the code

Asynchronous operations

  • Async methods and await asynchronous operations, just look at an example of a network request
static Future<ArticleListData> getArticleData(int pageNum) async{
    String path = '/article/list/$pageNum/json';
    Response response = await HttpUtils.get(Api.BASE_URL+path);
    ArticleBaseData articleBaseData = ArticleBaseData.fromJson(response.data);
    return articleBaseData.data;
  }
Copy the code

To learn more about Dart, check out the Dart language website

Flutter

The official documentation

  • flutter.dev
  • Because Chinese website

Flutter Hello world

  • Before starting the Flutter Hello World application, as an Android developer, we should first realize that There is no native DEVELOPED XML in Flutter. All the interface and logic code is in the.dart file. Flutter provides me with a set of visual, structural, platform, and interactive Widgets, so all the interface of the architecture in Flutter is Widgets. Next we will look at a simple Hello World Flutter application.

  • Android Studio creates a Flutter demo

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.blueAccent,
      ),
      home: new Scaffold(
        appBar: new AppBar(
            title: new Center(
              child: new Text("Welcome to Flutter"),
            )
        ),
        body: DemoStatelessWidget("Flutter Hello World ! Stateless widgets"),),); }} class DemoStatelessWidget extends StatelessWidget{final String text; // The constructor passes in the text value DemoStatelessWidget(this.text); @override Widget build(BuildContext context) { // TODO: implement buildreturnContainer( constraints: BoxConstraints.expand( height: Theme of (context). TextTheme. Display1. FontSize * 1.1 + 200.0), the padding: const EdgeInsets. All (8.0), color: Colors.blue[600], alignment: Alignment.center, child: Text(text, style: Theme. Of (context).textTheme.display1. CopyWith (color: colors.white)), transform: matrix4.rotationz (0.1),); }}Copy the code
  • The results

  • As shown in the code above, the main function first runs MyApp, which is a DemoStatelessWidget, literally a stateless Widget. Its build method creates the MaterialApp Widget that allows the app to run on the phone. We then created that Scaffold Widget that allows us to create the AppBar and the page content. The body page content contains a stateless DemoStatelessWidget that uses the constructor to pass in the actual page content we want. This widget contains a Text widget with a white background and real Text.

Flutter ListView

  • As you can probably guess from the StatelessWidget in the previous example, there must be a StatefulWidget. This widget is a StatefulWidget. The main thing is that in its managed State we can call setState to dynamically change the page display. Next, let’s look at an example of displaying a list of data and adding a button to favorites.
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart'; void main() => runApp(MyApp()); Class MyApp extends StatelessWidget {// StatelessWidgets are immutable, This means that their properties cannot be changed - all values are final. {return MaterialApp(
      //title: 'Welcome to Flutter', theme: ThemeData( primaryColor: Colors.blueAccent, ), home: new RandomWords(), ); StatefulWidget Class RandomWords extends StatefulWidget{@override createState() => new RandomWordsState(); } // Return ListView Widget class RandomWordsState extends State<RandomWords> {// Save a list of suggested word pairs (variables starting with an underscore (_), Using the underscore prefix identifier in the Dart language forces it to be private. final List _suggestions = new List<WordPair>(); // Final _biggerFont = const TextStyle(fontSize: 18.0); // Save a collection of favorite word groupssetFinal Set _saved = new Set<WordPair>(); /// State life cycle method @override voidinitState() {// state initializes super.initstate (); } @override voiddidChangeDependencies() {/ / after initState calls, access to other State at this time. Super didChangeDependencies (); } @override voiddispose() {// state dispose of super.dispose(); } @override Widget build(BuildContext context) { //returnnew Text(new WordPair.random().asPascalCase); // Return the ListView of the word pair.returnNew Scaffold(appBar: new appBar (title:new Center(// Centered child: new Text('Flutter ListView'), ), ), body: _buildSuggestions(), ); } // Build a ListView that displays suggested word pairs. Widget_buildSuggestions() {returnnew ListView.builder( padding: Const edgeinsets.all (16.0), // The itemBuilder is called once for each suggested word pair, and the word pair is added to the ListTile line // on the even line, This function adds a ListTile row to the word pairs. // On odd rows, this function adds a separator widget to separate adjacent word pairs. The itemBuilder value is an anonymous callback function that takes two arguments - BuildContext and line iterator I. The iterator starts at 0. // Each time the function is called, I increments by 1 and is executed once for each suggested pair of words. This model allows the list of suggested word pairs to grow indefinitely as the user scrolls. ItemBuilder: (context, I){// Add a 1 pixel high divider widget before each columnif(i.isOdd) returnnew Divider(); / / grammar"i ~/ 2"If I is 1, 2, 3, 4, 5 //, the result is 0, 1, 1, 2, 2. Final index = I ~/2; final index = I ~/2;if(index >= _suggestion.length){// If the last word pair in the suggested word list is then regenerated into 10 word pairs, Then add it to the suggestion_suggestion.addall (generateWordPairs().take(10)); }return_buildRow(_suggestions[index]); }); } // create a ListTile to display each new word on Widget _buildRow(WordPair suggestion) {// get whether the word state isSaved final isSaved = _saved.contains(suggestion);returnNew ListTile(// set the title: new Text(suggestion.aspascalcase, style: _biggerFont,), // the trailing icon: New Icon(// Star Icon status isSaved? Icons.favorite : Icons.favorite_border, color: isSaved ? Colors.deeporange: null,), onTap: (){// When the user clicks the ListTile button, the ListTile calls its onTap callbacksetState(() {// callsetState() triggers the build() method for the State object, which results in an update to the UIif(isSaved){
             _saved.remove(suggestion);
          }else{ _saved.add(suggestion); }}); }); }}Copy the code
  • Running effect

  • If you want to create a StatefulWidget, you can create a StatefulWidget. If you want to create a StatefulWidget, you can create a StatefulWidget. Okay, so now we see the _buildRow method, which builds the ListTile Widget, and it responds to the click event by going back to the onTap method, so when we click the ListTile, we can call the setState method in the onTap method to dynamically change the page display, That is, changing the favorites button (note that the setState method needs to be called in the State class).

  • State is periodic and includes three functions:

  1. InitState () : initialization method
  2. DidChangeDependencies () : Called after initState, at which point other states can be obtained
  3. Dispose () : state dispose
  • If you are using Android Studio, you can quickly create statelessWidgets and StatefulWidgets using shortcuts. The StatelessWidget shortcut is STL, and the StatefulWidget shortcut is STF.

Section summarizes

  • Flutter pages are built from widgets
  • There are two types of widgets: stateless widgets with fixed page content, and statefulwidgets with dynamic page content

The Widget quick reference

  • Before we can start development, we need to have a general idea of the basic common widgets.

layout Widget

  • Layouts are one of the first things you should know about a native interface when writing it. Flutter also provides a number of layout widgets. Here are some commonly used layout widgets
The name of the layout, The characteristics of description
Container Layout widgets with a single child element that can be set flexibly
Padding Having a single child element adds the specified padding to the child widget
Center Center the display of the child widgets
Align The child widgets are aligned and can be automatically resized based on the size of the child widgets.
Row You can have multiple child elements that line up the list of child widgets horizontally, similar to the LinerLayout orientation=”horizontal” native control
Column You can have multiple child elements and have a vertical list of child widgets, similar to the native LinerLayout orientation=”vertical”
Stack You can have multiple child elements, allowing the child widgets to simply stack together
Flow Widgets that implement streaming layout algorithms
ListView Scrollable list control
  • See the Flutter Widgets directory for more information about Flutter widgets.

Interface widgets

  • With a layout, we also need to fill the layout with various controls to make up our page. For example, when we develop a Material Design-style App, Flutter provides us with Material Components Widgets. Next, select some commonly used controls to learn more about Flutter. See the Material Components Widgets directory for more Widgets.
The name of the Widget The characteristics of description
MaterialApp It encapsulates the widgets that an application needs to implement Material Design. As you can see from the previous demo, it is typically an application top-level entry widget
Scaffold Basic realization of Material Design layout structure. This class provides apis for displaying drawers, snackbars, and bottom sheets.
Appbar Used in combination with scaffolding, you can set the page title and various buttons (toolbars)
BottomNavigationBar The bottom navigation bar makes it easy to switch between taps and browse top-level views
Drawer Used with scaffolding, the Scaffold edge slides horizontally to display the Material Design panel for navigation links in the application
RaisedButton Button in Material Design responds to click events (button)
IconButton A Material icon button, you can set the icon, click on the water wave animation
TextField Text input field (EditText)
image Display image widget(ImageView)
Text Single format TextView

Navigation bar back button listening

  • WillPopScope, return button interception can be implemented in a Flutter by WillPopScope
  • The following example provides two effects, a double click returns a Toast prompt (Toast library Fluttertoast: ^3.1.3), or a pop-up prompts dialog to exit.
import 'package:flutter/material.dart';

class AppPage extends StatefulWidget {
  @override
  _AppPageState createState() => _AppPageState();
}

class _AppPageState extends State<AppPage> {
    @override
  Widget build(BuildContext context) {
    returnWillPopScope(/// nested by WillPopScope, can be used to listen for logic handling Android's return key. Child: Container(), onWillPop: () async{return_doubleExitApp(); }); } // Double-click to exit the application bool_doubleExitApp() {if (_lastPressedAt == null ||
        DateTime.now().difference(_lastPressedAt) > Duration(seconds: 1)) {
      ToolUtils.ShowToast(msg: "Click exit app again"); _lastPressedAt = datetime.now ();return false;
    }
    //应用关闭直接取消 Toast
    Fluttertoast.cancel();
    return true; } /// if returnreturn new Future.value(false); Popped is not processed /// if returnedreturn new Future.value(true); /// Here you can pop the confirmation box through showDialog, and on return you can pop it through navigator.of (context).pop(true); Future<bool> _dialogExitApp(BuildContext Context) {return showDialog(
        context: context,
        builder: (context) => new AlertDialog(
          content: new Text("Quit or not"),
          actions: <Widget>[
            new FlatButton(onPressed: () => Navigator.of(context).pop(false), child:  new Text("Cancel")),
            new FlatButton(
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
                child: new Text("Sure")))); }}Copy the code

The last

  • Everything is difficult at the beginning. For Flutter, it can be said that the first step has been taken. For something that has not been tried, there may be fear at the beginning. This article will stop here, if there is any mistake in the article, please mention it to me, we learn and progress together, if you think my article helps you, please also give me a like and attention, and welcome to visit my personal blog.
  • Flutter Complete Open Source project: Github.com/maoqitian/f…

reference

  • Official website of Flutter
  • Because Chinese website
  • Dart Official website
  • Dart Language

About me

Blog:

  • Personal blog
  • The Denver nuggets
  • Jane’s book
  • Github

Mail: