Quick Start Learning with Flutter (2)

Table of contents

Introduction to Dart

Some important concepts of Dart

Dart syntax learning

variable

built-in types

Number

String

Boolean

List

Set

Map

Symbol

function

Parameter type (optional parameter, required parameter)

function as argument to another function

anonymous function

operator

Relational operators

type determination operator

assignment operator

Logical Operators

Bitwise and shift operators

conditional expression

Cascade operator(..)

Callback


Introduction to Dart


Dart is a computer programming language developed by Google. It is used for the development of web, servers, mobile applications and the Internet of Things. Dart is an object-oriented, class-defined, single-inheritance language.


Some important concepts of Dart

  • Variables and data types: Dart is a strongly typed language, variables need to explicitly declare types or use type inference. Dart supports a variety of data types, including numbers, strings, Boolean values, lists, maps, etc.

  • Functions: Functions in Dart are first-class citizens and can be passed as arguments to other functions and as return values. Functions can have named parameters, optional parameters, and default parameters.

  • Classes and Objects: Dart is an object-oriented language that supports the concepts of classes and objects. A class is a blueprint for an object and defines its properties and methods. Objects are instances of classes and can be created through constructors.

  • Inheritance and polymorphism: Dart supports class inheritance. One class can inherit the properties and methods of another class. Through inheritance, code can be reused and extended. Dart also supports polymorphism, allowing objects of subclasses to be referenced using references from parent classes.

  • Interface: An interface in Dart is a convention that defines the methods a class should implement. Classes in Dart can implement one or more interfaces to achieve polymorphism and code reuse.

  • Asynchronous programming: Dart has built-in support for asynchronous programming. Using the async and await keywords can easily handle asynchronous operations, such as network requests, file reading and writing, etc. Asynchronous operations in Dart can be Future, Stream or custom asynchronous functions.

  • Exception handling: Exception handling in Dart uses try-catch statements to catch and handle exceptions. Specific types of exceptions can be caught and corresponding processing logic executed as needed.

  • Generics: Dart supports generics, which can be used in classes, functions, and interfaces to increase code flexibility and reusability. Generics allow type parameters to be specified at compile time.

  • Mixins: Mixins in Dart are a code reuse mechanism that allow a set of methods and properties to be injected into a class to enhance its functionality without the need for inheritance.

  • Introduction and import: In Dart, you can use the import keyword to introduce other Dart files or libraries, and use the export keyword to export the contents of the current file to other files for use.

  • Anything stored in a variable is an object , and all objects are instances of a corresponding class . Both numbers, functions and nullare objects. All objects inherit from the Object class.

  • Although Dart is strongly typed, Dart can infer types, so type annotations are optional. If you want to explicitly state that no type is required, [need to use a special type dynamic] .

  • Dart supports generics like List <int>(list of integers) or List <dynamic>(list of objects of any type).

  • Dart supports top-level functions (these functions are not encapsulated in a class or object, all applications have at least one top-level function, for example), as well as main()functions bound to classes or objects ( static functions and instance functions respectively ). And support for creating functions within functions ( nested or local functions ).

  • Similarly, Dart supports top-level variables , as well as variables bound to classes or objects (static variables and instance variables). Instance variables are sometimes called fields or properties.

  • Unlike Java, Dart does not have the keywords "public", "protected" and "private". If an identifier begins with an underscore (_), it is private relative to the library.

  • Identifiers begin with a letter or underscore (_), followed by any combination of letters and numbers.

Dart syntax learning


variable

//这里会类型推断出是String类型,(使用var定义的变量值可以被修改)
var name = "Bob";

//也可显示指定变量类型
String name = "Bob";

//使用过程中从来不会被修改的变量, 可以使用 final 或 const定义。final修饰的值只能设置一次,可以理解为final修饰的变量是不可改变的,而const修饰的表示一个常量。
final name = 'Bob';
const bar = 1000000; // 压力单位 (dynes/cm2)

//final,const区别
区别一:final 要求变量只能初始化一次,并不要求赋的值一定是编译时常量,可以是常量也可以不是。而 const 要求在声明时初始化,并且赋值必需为编译时常量。区别二:final 是惰性初始化,即在运行时第一次使用前才初始化。而 const 是在编译时就确定值了。

built-in types


The Dart language supports the following built-in types:
Number
String
Boolean
List (also known as Array)
Map
Set
Rune (used to represent Unicode characters in strings)
Symbol

  • Number

There are two types of Number in Dart language: int double
string, and numbers can be converted to each other.

// String -> int
var one = int.parse('1');
assert(one == 1);

// String -> double
var onePointOne = double.parse('1.1');
assert(onePointOne == 1.1);

// int -> String
String oneAsString = 1.toString();
assert(oneAsString == '1');

// double -> String
String piAsString = 3.14159.toStringAsFixed(2);
assert(piAsString == '3.14');
  • String

var s1 = 'hello';
var s2 = 'world';

//字符串可以通过 ${expression} 的方式内嵌表达式
print("${s1}");

//可以使用 + 运算符来把多个字符串连接为一个
print('${s1  + s2}');
print(s1 + s2);
  • Boolean

Dart's type safety means you can't use if (nonbooleanValue) or assert (nonbooleanValue). Instead, you should explicitly check the value like this:

// 检查空字符串。
var fullName = '';
assert(fullName.isEmpty);

// 检查 0 值。
var hitPoints = 0;
assert(hitPoints <= 0);

// 检查 null 值。
var unicorn;
assert(unicorn == null);

// 检查 NaN 。
var iMeantToDoThis = 0 / 0;
assert(iMeantToDoThis.isNaN);
  • List

//定义一个List
var list = [1, 2, 3];
//获取list长度
print(list.length);
print(list.isEmpty);
print(list.isNotEmpty);
//倒序
print(list.reversed.toList());
//修改
print(list.fillRange(1,2,'hah'));//打印[1,hah,3]。
//获取指定下表的元素
list[1] = 1;
  • Set

(It is an unordered and non-repeating collection, so the value cannot be obtained through the index.)

// Set<String> names = {}; // 这样也是可以的。
// var names = {}; // 这样会创建一个 Map ,而不是 Set 。
var names = <String>{};
//添加元素
names.add('fluorine');
//获取Set长度
print(names.length);
  • Map

var gifts = {
  // Key:    Value
  'first': 'partridge',
  'second': 'turtledoves',
  'fifth': 'golden rings'
};

//或
var gifts = Map();
gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings';
  • Symbol

A Symbol object represents an operator or identifier declared in a Dart program. You may never need to use Symbol, but it is very useful when you want to refer to an API by name for an identifier. Because the name of the identifier will be changed after code compression, but the symbol of the identifier will not be changed. Get the Symbol of the identifier through the literal Symbol, that is, adding a # sign in front of the identifier.

#radix
#bar

function

//示例
bool isNoble(int atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}
//当函数中只有一句表达式,可以使用简写语法(也叫箭头语法)
bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;

Parameter type (optional parameter, required parameter)

//可选参数可以是命名参数或者位置参数,但一个参数只能选择其中一种方式修饰。
//命名参数
enableFlags(bold: true, hidden: false);
//位置可选参数,将参数放到 [] 中来标记参数是可选的
String say(String from, String msg, [String device]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  return result;
}

function as argument to another function

void printElement(int element) {
  print(element);
}
var list = [1, 2, 3];
// 将 printElement 函数作为参数传递。
list.forEach(printElement);

anonymous function

Most functions have names, such as main() and printElement(). You can also create functions without names, which are called anonymous functions.

var list = ['apples', 'bananas', 'oranges'];
list.forEach((item) {
  print('${list.indexOf(item)}: $item');
});

operator

arithmetic operators

//稍有不同的
assert(5 / 2 == 2.5); // 结果是双浮点型
assert(5 ~/ 2 == 2); // 结果是整型
assert(5 % 2 == 1); // 余数

Relational operators


== != > < >= <=

type determination operator


The as, is, and is! operators are used to handle type checking at runtime.
The is operator is used to determine whether a variable is a certain type of data.
is! is to determine whether the variable is not a certain type of data.
Use the as operator to force the object to a specific type. Generally, it can be considered as an abbreviation of the function called by the determined object after the is type determination.

if (emp is Person) {
  // Type check
  emp.firstName = 'Bob';
}
//使用 as 运算符进行缩写:
(emp as Person).firstName = 'Bob';

assignment operator


Use = to assign a value to a variable. When using the ??= operator, a value is assigned to the variable being assigned only if it is null.

// 将值赋值给变量a
a = value;
// 如果b为空时,将变量赋值给b,否则,b的值保持不变。
b ??= value;

Logical Operators


and or not

Bitwise and shift operators


In Dart, you can manipulate individual bits of a number independently. Normally integer types are manipulated using bitwise and shift operators.
& | ^ ~expr << >>

final value = 0x22;
final bitmask = 0x0f;

assert((value & bitmask) == 0x02); // AND
assert((value & ~bitmask) == 0x20); // AND NOT
assert((value | bitmask) == 0x2f); // OR
assert((value ^ bitmask) == 0x2d); // XOR
assert((value << 4) == 0x220); // Shift left
assert((value >> 4) == 0x02); // Shift right

conditional expression


condition ? expr1 : expr2
If the condition is true, execute expr1 (and return its value): Otherwise, execute and return the value of expr2.
expr1 ?? expr2
If expr1 is non-null, return the value of expr1; otherwise, execute and return the value of expr2.

Cascade operator(..)


The cascading operator (..) can perform a series of operations on the same object. In addition to calling functions, you can also access field properties on the same object. This often saves the step of creating temporary variables and results in smoother code.

querySelector('#confirm') // 获取对象。
  ..text = 'Confirm' // 调用成员变量。
  ..classes.add('important')
  ..onClick.listen((e) => windnow.alert('Confirmed!'));
//等价于下面的代码
var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));
//级联运算符还可嵌套
final addressBook = (AddressBookBuilder()
      ..name = 'jenny'
      ..email = '[email protected]'
      ..phone = (PhoneNumberBuilder()
      ..number = '415-555-0100'
      ..label = 'home')
      .build()).build();

Callback

In Flutter, you can use callback functions to handle the return value of an event or the result of an asynchronous operation. Here is a simple example showing how to use callback functions in Flutter

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Callback Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(
        title: 'Callback Demo',
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _result = '';

  void _showResult(String result) {
    setState(() {
      _result = result;
    });
  }

  void _doSomething() {
    // 模拟一个耗时操作
    Future.delayed(Duration(seconds: 2), () {
      String result = '操作完成';
      _showResult(result);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              onPressed: _doSomething,
              child: Text('执行操作'),
            ),
            SizedBox(height: 20),
            Text(
              _result,
              style: TextStyle(fontSize: 20),
            ),
          ],
        ),
      ),
    );
  }
}

In this example, we created a simple Flutter app containing a button and a text box. When the user clicks the button, a time-consuming operation is performed and the operation result is passed to the main page through the callback function. Then, we use setStatethe method to update the text box on the interface to display the results of the operation.

In _MyHomePageStatethe class, we define a _showResultmethod for updating the operation results. Then, in _doSomethingthe method, we use Future.delayedto simulate a time-consuming operation and call _showResultthe method to update the interface after the operation is completed.

Guess you like

Origin blog.csdn.net/yuhui77268769/article/details/132880666