Dart 基础
最近在学移动应用开发的,为了使用Flutter框架先学一些Dart的基础。dart的写法是结合js和java的,因此后面只给出了一些dart语言的特殊写法及案例。
前言
谷歌推出Flutter跨平台UI框架后,对移动端开发产生了新的影响,Flutter采用了Dart语言开发。Dart语法结合Java和javaScript语法特点,可以让有基础的程序员快速上手。
变量声明
允许变量为null
String? number;
不允许变量为null(在对该变量赋值之前无法使用该变量)
late String number;
number = "123";
变量类型转换
void main() {
var one = int.parse("1");
assert(one == 1); // 用于检查是否正确
var onePointOne = double.parse("1.1");
assert(onePointOne == 1.1);
String oneAsString = one.toString();
assert(oneAsString == "1");
String piAsString = 3.1415926.toStringAsFixed(2);
assert(piAsString == "3.14");
}
数组
利用类似于Python的列表推导
var listOfInts = [1,2,3];
var listOfStrings = ["#0", for(var i in listOfInts) if (i != 2) "#$i"];
print(listOfStrings);
Set集合
void test() {
var listOfInts = [1,2,3];
var listOfStrings = ["#0", "#0", for(var i in listOfInts) if (i != 2) "#$i"];
var names = <String>{};
names.add(1.toString());
names.addAll(listOfStrings);
print(names);
print(names.length);
}
output
{1, #0, #1, #3}
4
Maps
字面量创建map
void test() {
var gifts = {
"first": 1,
"second": "2",
};
print(gifts);
}
使用Map的构造器创建Map
void test() {
var gifts = Map<String, String>();
gifts["first"] = "1";
gifts["second"] = "2";
print(gifts);
}
各种循环
void test() {
var gifts = Map<String, String>();
gifts["first"] = "1";
gifts["second"] = "2";
gifts.forEach((key, value) => print("das"));
const list = ["apples", "bananas", "oranges"];
list.forEach((element) => print(element));
for (var i = 0; i < list.length; i++){
print(list[i]);
}
for (var element in list) {
print(element);
}
}
错误抛出
void test() {
throw FormatException("抛出错误");
}
void test() {
const list = [1,2,3];
try {
print(list[3]);
} catch (e) {
print("Error: $e");
} finally {
print("finally");
}
}
类
class Point {
double? x, y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
get X { return this.x! + 1.1; }
String GetDiction () {
return this.X.toString() + "===>" + this.y.toString();
}
}
void test() {
var p1 = new Point(1.1, 2.2);
var dir = p1.GetDiction();
print(dir);
}
函数
将参数放入[]
中标记参数可选, 同时可以设置参数的默认值
String say(String name, [int? age,String message = "dsadas"]) {
assert(name != "");
if (message == null) {
return "未输入内容";
}
return "name : ${name} age : ${age} say : ${message}";
}
void test() {
const person = "Ywh";
print(say(person, 16));
}
匿名函数
void test() {
int Function(int a,int b) Add = (int a, b) => a + b;
print(Add(1,2));
}
泛型
T First<T>(List<T> a) {
assert(a.length > 0);
return a[0];
}
void test() {
const names = ["1", "2"];
print(First(names));
}