跳到主要内容

Flutter 和 Dart 速查表

本页面汇总了 Flutter 和 Dart 开发中最常用的语法和知识点,方便快速查阅。

Dart 速查

变量声明

var name = '张三';              // 类型推断
final age = 25; // 运行时常量
const pi = 3.14159; // 编译时常量
String city = '北京'; // 显式类型
int? nullableVar; // 可空变量
late String lateVar; // 延迟初始化

数据类型

// 数值
int age = 25;
double price = 19.99;
num value = 10;

// 字符串
String name = '张三';
String greeting = '你好,$name!';
String multiline = '''
多行
字符串
''';

// 布尔
bool isActive = true;

// 列表
List<int> numbers = [1, 2, 3];
numbers.add(4);
numbers.remove(2);

// 集合
Set<String> fruits = {'苹果', '香蕉'};
fruits.add('橙子');

// 映射
Map<String, int> scores = {'张三': 90, '李四': 85};
scores['王五'] = 95;

运算符

// 算术
a + b // 加
a - b // 减
a * b // 乘
a / b // 除
a ~/ b // 整除
a % b // 取余

// 比较
a == b // 等于
a != b // 不等于
a > b // 大于
a < b // 小于

// 逻辑
a && b // 与
a || b // 或
!a // 非

// 条件
a ?? b // 空值合并
a?.length // 空值感知
condition ? a : b // 三元运算符

控制流

// if-else
if (condition) {
// ...
} else if (condition) {
// ...
} else {
// ...
}

// switch
switch (value) {
case 'A':
// ...
break;
default:
// ...
}

// for 循环
for (int i = 0; i < 10; i++) {
// ...
}

for (var item in list) {
// ...
}

// while 循环
while (condition) {
// ...
}

do {
// ...
} while (condition);

函数

// 基本函数
int add(int a, int b) => a + b;

// 可选参数
String greet(String name, [String greeting = '你好']) {
return '$greeting,$name!';
}

// 命名参数
void printUser({required String name, int age = 18}) {
print('$name, $age');
}

// 函数作为参数
void forEach(List<int> list, void Function(int) action) {
for (var item in list) action(item);
}

// 箭头函数
var square = (int x) => x * x;

class Person {
String name;
int age;

Person(this.name, this.age);

Person.guest() : name = '访客', age = 0;

void sayHello() => print('你好,$name');

@override
String toString() => 'Person($name, $age)';
}

// 继承
class Dog extends Animal {
Dog(String name) : super(name);

@override
void speak() => print('汪汪');
}

// Mixin
mixin Swimmable {
void swim() => print('游泳');
}

class Duck extends Animal with Swimmable {}

异步

// Future
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 1));
return '数据';
}

// 使用
void getData() async {
final data = await fetchData();
print(data);
}

// Stream
Stream<int> countStream() async* {
for (int i = 1; i <= 5; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}

// 监听 Stream
await for (var count in countStream()) {
print(count);
}

Flutter 速查

基础 Widget

// 文本
Text('Hello', style: TextStyle(fontSize: 24));

// 按钮
ElevatedButton(onPressed: () {}, child: Text('按钮'));
TextButton(onPressed: () {}, child: Text('按钮'));
IconButton(onPressed: () {}, icon: Icon(Icons.star));

// 图片
Image.network('https://example.com/image.jpg');
Image.asset('assets/image.png');
Icon(Icons.star, size: 48, color: Colors.yellow);

// 容器
Container(
width: 100,
height: 100,
padding: EdgeInsets.all(8),
margin: EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(8),
),
child: Text('内容'),
);

布局 Widget

// 行
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [Text('A'), Text('B')],
);

// 列
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [Text('A'), Text('B')],
);

// 展开
Expanded(flex: 2, child: Container());

// Stack
Stack(
children: [
Container(),
Positioned(top: 10, left: 10, child: Container()),
],
);

// 换行
Wrap(
spacing: 8,
runSpacing: 8,
children: [Chip(label: Text('A')), Chip(label: Text('B'))],
);

列表

// ListView
ListView.builder(
itemCount: 100,
itemBuilder: (context, index) {
return ListTile(title: Text('项目 $index'));
},
);

// GridView
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
),
itemCount: 20,
itemBuilder: (context, index) {
return Card(child: Center(child: Text('$index')));
},
);

输入

// TextField
TextField(
controller: _controller,
decoration: InputDecoration(
labelText: '用户名',
hintText: '请输入',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.person),
),
onChanged: (value) => print(value),
);

// 开关
Switch(value: _isOn, onChanged: (v) => setState(() => _isOn = v));

// 复选框
Checkbox(value: _isChecked, onChanged: (v) => setState(() => _isChecked = v!));

// 单选按钮
Radio(value: 1, groupValue: _selected, onChanged: (v) => setState(() => _selected = v!));

导航

// 基本导航
Navigator.push(context, MaterialPageRoute(builder: (_) => SecondPage()));
Navigator.pop(context);

// 命名路由
Navigator.pushNamed(context, '/detail', arguments: {'id': 123});

// GoRouter
context.go('/detail/123');
context.push('/detail/123');
context.pop();

状态管理

// setState
setState(() => _counter++);

// Provider
ChangeNotifierProvider(
create: (_) => Counter(),
child: MyApp(),
);

Consumer<Counter>(
builder: (context, counter, _) {
return Text('${counter.count}');
},
);

网络请求

// http 包
final response = await http.get(Uri.parse('https://api.example.com/data'));
final data = jsonDecode(response.body);

// Dio
final dio = Dio();
final response = await dio.get('/users');
final users = response.data;

文件操作

// 上传
final formData = FormData.fromMap({
'file': await MultipartFile.fromFile(filePath),
});
await dio.post('/upload', data: formData);

// 下载
await dio.download(url, savePath);

常用属性

EdgeInsets

EdgeInsets.all(16)                    // 四边相同
EdgeInsets.symmetric(horizontal: 16) // 水平方向
EdgeInsets.only(left: 16, top: 8) // 指定方向
EdgeInsets.fromLTRB(16, 8, 16, 8) // 左上右下

BoxDecoration

BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.black, width: 1),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 10,
offset: Offset(0, 4),
),
],
gradient: LinearGradient(
colors: [Colors.blue, Colors.green],
),
)

TextStyle

TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.blue,
letterSpacing: 2,
height: 1.5,
decoration: TextDecoration.underline,
)

生命周期

StatefulWidget

initState()           // 初始化
didChangeDependencies() // 依赖改变
build() // 构建 UI
didUpdateWidget() // Widget 更新
dispose() // 销毁清理

应用生命周期

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}

@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.resumed:
print('应用恢复');
break;
case AppLifecycleState.paused:
print('应用暂停');
break;
case AppLifecycleState.inactive:
print('应用非活动');
break;
case AppLifecycleState.detached:
print('应用分离');
break;
}
}

@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
}

常用命令

# 创建项目
flutter create my_app

# 运行项目
flutter run
flutter run -d chrome

# 构建
flutter build apk
flutter build ios
flutter build web

# 获取依赖
flutter pub get

# 清理
flutter clean

# 检查环境
flutter doctor

# 升级
flutter upgrade

小结

本速查表涵盖了 Flutter 和 Dart 开发的常用语法和知识点:

  1. Dart 基础:变量、数据类型、控制流、函数、类
  2. Flutter Widget:基础 Widget、布局、列表、输入
  3. 导航和状态管理
  4. 网络请求和文件操作
  5. 常用属性和生命周期
  6. 常用命令

建议将本页面收藏,作为日常开发的快速参考。