UI控件库与程序入口
Dart
import 'package:flutter/material.dart';
// 相当于 Swift 里的 import UIKit 或 import SwiftUI。
导入 Flutter 官方提供的 Material Design(谷歌设计语言)UI 控件库(用于安卓或者MaterialDesign) 。 Scaffold、AppBar、Text、Icon、FloatingActionButton 等基础 UI 组件,全部都是在这个文件里定义的。如果不导入它,Dart 编译器就无法识别这些 Widget。
如果是iOS,就导入这个库
Dart
import 'package:flutter/cupertino.dart';
// 相当于 Swift 里的 import UIKit 或 import SwiftUI。
通过以下第一行来指定程序入口
Dart
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: NewWidget(),
);
}
}
Swift vs Dart 核心语法对照表
| 概念 / 语法 | Swift 语法示例 | Dart 语法示例 | 区别与注意事项 |
|---|---|---|---|
| 变量声明 | var count = 10 |
var count = 10; |
均支持类型推导;Dart 语句结尾必须加分号 |
| 运行时常量 | let name = "Swift" |
final name = "Dart"; |
Dart 的 final 对应 Swift 的 let |
| 编译时常量 | static let max = 100 |
const max = 100; |
Dart 的 const 为编译时确定且深不可变 |
| 基础数值类型 | Int, Double, Float |
int, double |
Dart 中 int 和 double 都继承自 num |
| 布尔类型 | Bool (true / false) |
bool (true / false) |
名称首字母大小写不同 |
| 字符串与插值 | "Hello \(name)" |
'Hello $name' 或 'Hello ${name.upper}' |
Dart 支持单/双引号;单变量可省略 {} |
| 列表/数组 | var list: [Int] = [1, 2] |
List<int> list = [1, 2]; |
Dart 统一称为 List |
| 字典/映射 | var dict = ["a": 1] |
Map<String, int> dict = {'a': 1}; |
Dart 称为 Map,字面量用大括号 {} |
| 集合 | var set: Set = [1, 2] |
Set<int> set = {1, 2}; |
两者基本一致 |
| 可空类型 | String? |
String? |
空安全标识符相同 |
| 空合并运算符 | a ?? defaultVal |
a ?? defaultVal |
完全一致 |
| 强制解包 | x! |
x! |
完全一致 |
| 结构体/值类型 | struct Point { var x: Int } |
❌ 无 struct |
核心差异:Dart 只有类(引用类型) |
| 类与继承 | class Dog: Animal |
class Dog extends Animal |
Dart 继承使用 extends 关键字 |
| 构造函数 | init(name: String) { self.name = name } |
Dog(this.name); |
Dart 支持 this.name 自动赋值语法糖 |
| 协议/接口 | protocol Measurable |
abstract class / interface class |
Dart 没有 protocol 关键字,类皆可作为接口 |
| 组合/混入 | extension / protocol 扩展 |
mixin / with |
Dart 使用 mixin 实现跨类代码复用 |
| 扩展方法 | extension String { ... } |
extension StringExt on String { ... } |
Dart 的扩展通常需要显式命名 |
| 异步处理 | async / await (Task) |
async / await (Future) |
Dart 用 Future<T> 表示异步单值 |
| 异步数据流 | AsyncSequence |
Stream<T> |
Dart 内置 Stream 处理多值事件流 |
创建页面(Widget)
创建类,继承StatefulWidget。这是类似Swift里的ViewController的,但不同的是,Dart的所有UI都是在Widget树上的,并关联到State,类似SwiftUI里的@State
Dart
class NewWidget extends StatefulWidget {
const NewWidget({super.key});
@override
State<NewWidget> createState() => _NewWidgetState();
// 创建并关联widget到State
}
创建私有类,继承以上,然后在里面封装一些方法
Dart
class _NewWidgetState extends State<NewWidget> {
// 私有类,状态与UI的地方,_表私有
int _count = 0;
@override
void initState() {
// 相当于viewDidLoad
super.initState();
print("页面加载了");
}
void _incrementCount() {
setState(() {
// 通知框架状态变更
_count++;
// 就是count += 1
});
}
写UI,真正在页面上布局
appBar就是导航栏,Center就是中心。
child表示子组件,Column就是垂直=VStack; Row就是水平
children能装一排子组件, 接收一个数组.
Dart
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('一个计数器')),
body: Center(
child: Column(
// child表示子组件,Column就是垂直=VStack; Row就是水平
// children能装一排子组件, 接收一个数组
children: [
Text(
'点击次数: $_count',
style: const TextStyle(fontSize: 20),
),
const Text(
'这是一段文字捏,如果太长的话就 没有办法显示了喵喵喵qwq喵喵喵qwq喵喵喵qwq',
textAlign: TextAlign.center,
// 对齐
maxLines: 2,
// 最大行数
overflow: TextOverflow.ellipsis,
// 超出显示省略号
style: TextStyle(
fontSize: 20.0,
// 字号
fontWeight: FontWeight.bold,
color: Colors.blue,
letterSpacing: 1.5,
// 字间距
height: 1.2,
),
),
ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child:
Image.network(
'https://images.unsplash.com/photo-1507525428034-b723cf961d3e',
// 网络图片
width: 200,
height: 200,
fit: BoxFit.cover,
//填充模式,等比例缩放并填满
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCount,
// 给按钮绑定上面那个函数事件
child: const Icon(Icons.add),
// 按钮内展示一个+图标
),
);
}
}
文字组件就是Text
和SwiftUI非常类似,只有一些语法区别,设置属性也是类似的办法
Dart
Text(
'点击次数: $_count',
style: const TextStyle(fontSize: 20),
),
const Text(
'这是一段文字捏,如果太长的话就 没有办法显示了喵喵喵qwq喵喵喵qwq喵喵喵qwq',
textAlign: TextAlign.center,
// 对齐
maxLines: 2,
// 最大行数
overflow: TextOverflow.ellipsis,
// 超出显示省略号
style: TextStyle(
fontSize: 20.0,
// 字号
fontWeight: FontWeight.bold,
color: Colors.blue,
letterSpacing: 1.5,
// 字间距
height: 1.2,
),
图片组件就是Image
这只演示获取网络图片,非常方便只需要输入URL就能直接显示
ClipRRect(
borderRadius: BorderRadius.circular(16.0),则是设置图片圆角的方法
Dart
ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child:
Image.network(
'https://images.unsplash.com/photo-1507525428034-b723cf961d3e',
// 网络图片
width: 200,
height: 200,
fit: BoxFit.cover,
//填充模式,等比例缩放并填满
),
),
FloatingActionButton就是浮动的组件按钮(系统的),可以通过onPressed绑定点击事件。
如图绑定上面的私有类里的函数_incrementCount,实现点击一次,就计数一次的效果。然后给按钮设置一个官方的图标,名为add.
Dart
floatingActionButton: FloatingActionButton(
onPressed: _incrementCount,
// 给按钮绑定上面那个函数事件
child: const Icon(Icons.add),
// 按钮内展示一个+图标
),
);
}
}