阅读 306

【Flutter】 自学(二)-dart语言基础语法

声明变量

dynamic ,var,object 三种类型的区别

  • dynamic :所有dart 对象的基础类型,在大多数情况下,不直接使用它

通过它定义的变量会关闭类型检查,这意味着 dynamix x= 'hal'; x.foo(); 这段代码静态类型检查不会报错,但是运行时会crash,因为x 并没有foo() 方法,所以建议大家在编程时不要直接使用dynamic;

  • var :是一个关键字,意思是"我不关心这里的类型是什么",系统会自动判断类型
  • object : 是Dart 对象的基类;

dynamic 与object 的最大的区别是在静态类型检查上

String str = "Hello World";
var str2 = "Hello World";
复制代码

声明常量

final,const两种方式
//后占内存,用的时候才去申请内存空间
final abc = "1111";
//先占内存,一开始就申请内存空间
const bcd ="2222";
复制代码

数据类型

void main() {
  //int 类型
  int a = 100;
  //double 类型
  double b = 200.01;
  //num声明
  num c = 123.123;
  //打印出来是double类型
  print(c.runtimeType);
  //保留2位小数 四舍五入
  String d = 3000.555444.toStringAsFixed(2);
  //打印出来3000.56
  print(d);
  //true
  bool result = 123 > 122;
  print(result);
  //false
  bool result2 = 1 == '1';
  print(result2);
  
    //List
  List list = [1, 3, 5, 7];
  list.add(9);
  list.addAll([11, 13, 15]);
  //[1, 3, 5, 7, 9, 11, 13, 15]
  print(list);
  //8
  print(list.length);
  //15
  print(list.last);
  //5
  print(list[2]);
  //Map
  Map map = {'x': 1, 'y': 2, 'z': 3};
  Map map2 = new Map();
  map2['x'] = 1;
  map2['y'] = 2;
  //{x: 1, y: 2, z: 3}
  print(map);
  //{x: 1, y: 2}
  print(map2);
  //true
  print(map2.containsKey('x'));
  //false
  print(map2.containsKey('a'));
  map2.remove('x');
  //{y: 2}
  print(map2);
}
复制代码

Function

void main() {
  String name = getUserName();
  String userInfo = getPersonInfo(111);
  //张三
  print(userInfo);
  //默认值
  int age = addAge2(age1: 2, age2: 1);
  //匿名函数
  List list = ["111", "222"];
  list.forEach((element) {
    print(element);
  });
}
String getUserName() {
  return "Hello World";
}
String getPersonInfo(int userId) {
  Map info = {'111': "张三", '222': "李四"};
  return info[userId.toString()];
}
/// 可选参数[]
int addAge(int age1, [int age2]) {
  return age1 + (age2 == null ? 0 : age2);
}
///默认值
int addAge2({int age1, int age2 = 0}) {
  return age1 + age2;
}
复制代码

类与集成

void main() {
  var person = new Person(18, "张三");
  print(person.age);
  person.sayHello();
  var worker = new Worker(20, "李四", 3500);
  worker.sayHello();
}
class Person {
  //属性
  int age;
  String name;
  //构造函数
  Person(int age, String name) {
    this.age = age;
    this.name = name;
  }
  //成员方法
  void sayHello() {
    print("my name is" + this.name);
  }
}
///子类
class Worker extends Person {
  int salary;
  Worker(int age, String name, int salary) : super(age, name) {
    this.salary = salary;
  }
  @override
  void sayHello() {
    super.sayHello();
    print("my salary is" + this.salary.toString());
  }
}
注意:extends只能是单继承 ,with 可以相当于继承多个
class Eat {
  void eat() {}
  void speak() {
    print("speak in Eat");
  }
}
class Sleep {
  void sleep() {}
  void speak() {
    print("speak in Sleep");
  }
}
class Student with Eat, Sleep {}
  var student = new Student();
  //speak in Sleep,同收有相同方法,以后面的为准
  student.speak();
抽象类
abstract class Animal {
  //子类必须继承
  void abc();
    //子类可选择继承
  void bcd() {
    print("bcd");
  }
}
复制代码

库的使用

我们自己项目里面写的库使用,import 导入,就可以使用相关的方法了

import 'pkg/Calc.dart';
复制代码

使用别人写的库 需要通过pub引入 pub.dev 打开之后搜索自己想用的库,比如:http

然后执行命令行

flutter pub get
复制代码

使用如下:

import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
void main(List<String> arguments) async {
  // This example uses the Google Books API to search for books about http.
  // https://developers.google.com/books/docs/overview
  var url = 'https://www.googleapis.com/books/v1/volumes?q={http}';
  // Await the http get response, then decode the json-formatted response.
  var response = await http.get(url);
  if (response.statusCode == 200) {
    var jsonResponse = convert.jsonDecode(response.body);
    var itemCount = jsonResponse['totalItems'];
    print('Number of books about http: $itemCount.');
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}
复制代码

延时加载 deferred as ,使用之前调用 loadLibrary()

//延时按需加载
import 'dart:math' deferred as math;
void main() async {
  await math.loadLibrary();
  var abc = new math.Random();
  print(abc.nextInt(10));
}
复制代码

异步处理

使用Future

void main(){
  print("start");
  
  Future.delayed(new Duration(seconds: 5),(){
    print("吃饱了");
  });
  print("end");
}
复制代码

吃饱了是异步操作,我们想先吃饱了在结束,也就是异步同步写法,怎么弄呢?就需要要使用asyncawait

void main() async{
  print("start");
  
  await Future.delayed(new Duration(seconds: 5),(){
    print("吃饱了");
  });
  print("end");
}
复制代码

多个异步同时进行,都结束了在往下执行

void main() async {
  print("start");
  Future.wait([
    Future.delayed(new Duration(seconds: 1), () {
      print("第一个");
    }),
    Future.delayed(new Duration(seconds: 5), () {
      print("第二个");
    }),
    Future.delayed(new Duration(seconds: 3), () {
      print("第三个");
    })
  ]).then((value) => {print("all end")});
}
复制代码
文章分类
Android
文章标签