Flutter 入门笔记(Part 0) Dart入门知识

2773次阅读  |  发布于3年以前

接下来的一段时间,我会推一些学习Flutter过程中的笔记,取需.

1 . Dart 基础语法

1.1 hello world

先来看个hello world,入口依然是main方法.

printInteger(int a) {
  print('Hello world, this is $a.'); 
}

main() {
  var number = 2019; 
  printInteger(number); 
}

1.2 变量与类型

var a = 1;
int b = 1;
num c = 3;

int x = 1;
int hex = 0xEEADBEEF;
double y = 1.1;
double exponents = 1.13e5;
int roundY = y.round();

//List
var arr1 = ["Tom", "Andy", "Jack"];
var arr3 = <String>["Tom", "Andy", "Jack"];
var arr2 = List.of([1, 2, 3]);
var arr4 = List<int>.of([1, 2, 3]);
arr2.add(499);
arr2.forEach((v) => print(v));

//Map
var map1 = {"name": "Tom", "sex": "male"};
var map2 = new Map();
//添加或修改
map2["name"] = "Tom";
map2["name"] = "Tom22";
map2["sex"] = "male";

print(map2);
map2.forEach((k, v) => print('k = $k v=$v'));

1.3 函数

void main() {
  Function f = isZero;
  int x = 10;
  int y = 10;
  printInfo(x, f);
  printInfo(y, f);

  enable1Flags(bold: true);
}

bool isZero(int a) {
  return a == 0;
}

bool isNull(var a) => a == null;

void printInfo(int number, Function check) {
  print('$number is zero: ${check(number)}');
}

//可选命名参数   Flutter 中大量使用
void enable1Flags({bool bold, bool hidden}) => print("$bold $hidden");

//可选命名参数 加默认值
void enable2Flags({bool bold = true, bool hidden = false}) =>
    print('$bold $hidden');

//可忽略参数,也可以加默认值
void enable3Flags(bool bold, [bool hidden]) => print("$bold $hidden");

//返回值类型 省略
price() {
    double sum = 0.0;
    for (var i in booking) {
      sum += i.price;
    }
    return sum;
}

1.4 类

void main() {
  //类 都是继承自Object
  //无修饰符关键字 变量与方法前面加"_"则表示private,不加则为public
  //加"_"的限制范围并不是类访问级别的,而是库访问级别的
  Test test = Test();
  print(test.b);

  var p = Point(1, 2);
  p.printInfo();
  Point.factor = 10;
  Point.printZValue();
  //为空时跳过执行
  Point?.printZValue();

  var p2 = Point2.test(1);
}

class Test {
  int _a = 1;
  int b = 2;
}

class Point {
  num x, y;
  static num factor = 0;

  //语法糖,等同于在函数体内:this.x = x;this.y = y;
  Point(this.x, this.y);

  void printInfo() => print('($x,$y)');

  static void printZValue() => print('factor=$factor');
}

class Point2 {
  num x, y, z;

  //z也得到了初始化
  Point2(this.x, this.y) : z = 0;

  //重定向构造函数
  Point2.test(num x) : this(x, 0);
}

class Point3 {
  num x = 0, y = 0;

  void printInfo() => print('($x,$y)');
}

class Vector extends Point3 {
  num z = 0;

  //覆写了父类的方法
  @override
  void printInfo() => print('x = $x,y=$y');
}

class Coordinate implements Point3 {
  //成员变量需要重新声明
  num x = 0, y = 0;

  //成员函数需要重新实现
  @override
  void printInfo() {}
}

//混入Mixin  可以视为具有实现方法的接口
//非继承的方法,使用其他类中的变量与方法
class Coordinate2 with Point3 {}

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8