(Flutter)语法
基础类型与变量声明
void main() {
var name = 'Alice'; // String
var age = 25; // int
var height = 1.68; // double
var isStudent = true; // bool
final currentTime = DateTime.now(); // 运行时确定
const maxAttempts = 3; // 编译时确定
print('Name:${name}\r\nAge:${age}\r\nheight:${height}');
print('Time:${currentTime.hour}:${currentTime.minute}');
}
列表
void main() {
// 有序列表,允许重复
var shoppingList = ['牛奶', '面包'];
shoppingList.add('鸡蛋');
shoppingList.removeAt(0);
print('待购物品: ${shoppingList.join(', ')}');
// 无序集合,不允许重复
var uniqueNumbers = {1, 2, 2, 3};
uniqueNumbers.add(9);
print(uniqueNumbers); // 输出:{1, 2, 3}
// 类型混合List
var dynamicList = [1, '二', true];
print('${dynamicList.join(',')}');
}
函数与传参
String greet([String name = 'Ycp666',String time = '早晨']) {
return '$time好,$name!';
}
void main() {
// if-else与循环
for (var i = 1; i <= 5; i++) {
if (i % 2 == 0) {
print('$i 是偶数');
} else {
print('$i 是奇数');
}
}
// 函数调用
print(greet()); // 使用默认参数
print(greet('Charlie', '下午'));
}
高阶函数
final numbers = [1, 2, 3, 4, 5, 6];
int sq(int n) {
return n * n;
}
void main() {
// .toList用于把squared转化为列表,方便使用列表特有函数
final squared = numbers.map((n) => sq(n)).toList();
print('平方: $squared\r\n');
// 组合操作:过滤偶数并求和
final evenSum = numbers.where((n) => n % 2 == 0).reduce((a, b) => a + b);
print('偶数和: $evenSum'); // 6
print(numbers);
// 自定义高阶函数
void repeat(Function(int, int) action, int times) {
for (var i = 0; i < times; i++) {
action(i, 1);
}
}
repeat((index, index2) => sq(index), 3);
//有返回值的自定义高阶函数,<T>代表自定义类型
List<T> repeat2<T>(Function(int, int) action, int times) {
List<T> results = [];
for (var i = 0; i < times; i++) {
// 调用 action 函数并将返回值添加到 results 列表中
results.add(action(i, 1) as T);
}
return results;
}
List<int> resultList = repeat2((index, index2) => sq(index), 3);
print(resultList);
}
类和继承
// 接口定义
abstract class SoundEmitter {
void makeSound();
}
// 基类
class Animal implements SoundEmitter {
// 相当于函数的传入参数
String name,name2;
Animal(this.name,this.name2);
@override
void makeSound() => print('$name 发出声音');
}
// 混入,使得其他类支持 .fly方法
mixin Flyable {
void fly(){
print('Fly');
}
}
class Bird extends Animal with Flyable {
// 传入参数,同时传递到父类
double wingspan;
Bird(String name, this.wingspan) : super(name,'1');
@override
void makeSound() {
super.makeSound();
print('啾啾鸣叫');
}
// 命名构造函数
Bird.init() : this('麻雀', 0.3);
}
void main() {
final bird = Bird.init();
bird.makeSound();
// bird.fly();
}
异步编程
import 'dart:async';
// 模拟网络请求
Future<String> fetchUserData(int id) async {
await Future.delayed(Duration(seconds: 5));
return '用户$id: Alice (VIP会员)';
}
void main() async {
try {
// 并行请求
final results = await Future.wait([
fetchUserData(101),
fetchUserData(102),
]);
print('批量获取: $results');
// Stream处理
final controller = StreamController<int>();
controller.stream
.where((n) => n > 3)
.listen((data) => print('收到数据: $data'));
for (var i = 1; i <= 5; i++) {
controller.add(i);
}
await controller.close();
} catch (e) {
print('请求失败: $e');
}
}
License:
CC BY 4.0