附录A 快速参考指南¶
Kotlin / Compose / Flutter / Gradle / Git 速查表
1. Kotlin 速查表¶
基础语法¶
Kotlin
// 变量声明
val immutable = "不可变" // 只读
var mutable = "可变" // 可修改
// 空安全
var nullable: String? = null // 可为null
var nonNull: String = "值" // 不可为null
// 安全调用
val length = nullable?.length // null时返回null
val len = nullable?.length ?: 0 // null时使用默认值
// 非空断言(谨慎使用)
val risky = nullable!!.length // null时抛出NPE
函数¶
Kotlin
// 基本函数
fun greet(name: String): String {
return "Hello, $name"
}
// 单表达式函数
fun greet(name: String) = "Hello, $name"
// 默认参数
fun greet(name: String, greeting: String = "Hello") = "$greeting, $name"
// 命名参数
greet(name = "Alice", greeting = "Hi")
// 高阶函数
fun operate(a: Int, b: Int, op: (Int, Int) -> Int) = op(a, b)
val sum = operate(1, 2) { x, y -> x + y }
类与对象¶
Kotlin
// 数据类
data class User(val id: String, val name: String)
// 使用
val user = User("1", "Alice")
val copy = user.copy(name = "Bob")
val (id, name) = user // 解构
// 密封类
sealed class Result<out T>
data class Success<T>(val data: T) : Result<T>() // 泛型<T>:类型参数化
data class Error(val exception: Exception) : Result<Nothing>()
// 单例
object DatabaseHelper
// 伴生对象
class MyClass {
companion object {
const val VERSION = "1.0"
fun create() = MyClass()
}
}
协程¶
Kotlin
// 启动协程
val scope = rememberCoroutineScope()
scope.launch { /* 后台任务 */ }
val deferred = scope.async { /* 返回结果 */ }
val result = deferred.await()
// Flow
val flow = flow {
emit(1)
emit(2)
}
// 收集
flow.collect { value -> println(value) }
// 操作符
flow.map { it * 2 }.filter { it > 2 }.collect { }
2. Jetpack Compose 速查表¶
基础组件¶
Kotlin
// 文本
Text("Hello", style = MaterialTheme.typography.bodyLarge)
Text(text = "Hello", fontSize = 16.sp, color = Color.Red)
// 按钮
Button(onClick = { }) { Text("Click") }
OutlinedButton(onClick = { }) { }
TextButton(onClick = { }) { }
IconButton(onClick = { }) { Icon(Icons.Default.Add, null) }
// 图片
Image(painter = painterResource(R.drawable.image), contentDescription = null)
AsyncImage(model = url, contentDescription = null)
// 输入框
var text by remember { mutableStateOf("") }
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") }
)
布局¶
Kotlin
// Column - 垂直排列
Column(
modifier = Modifier.fillMaxSize().padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Item 1")
Text("Item 2")
}
// Row - 水平排列
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text("Left")
Text("Right")
}
// Box - 层叠
Box(modifier = Modifier.fillMaxSize()) {
Text("Bottom", modifier = Modifier.align(Alignment.BottomCenter))
}
// Lazy列表
LazyColumn {
items(dataList) { item ->
ItemComposable(item)
}
}
状态管理¶
Kotlin
// remember
val count = remember { mutableStateOf(0) }
Text("${count.value}")
// rememberSaveable(配置变更保留)
var text by rememberSaveable { mutableStateOf("") }
// derivedStateOf
val isEnabled by remember { derivedStateOf { count.value > 0 } }
// ViewModel
class MyViewModel : ViewModel() {
private val _uiState = MutableStateFlow(UiState())
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
}
@Composable
fun MyScreen(viewModel: MyViewModel = hiltViewModel()) {
val state by viewModel.uiState.collectAsState()
}
Modifier¶
Kotlin
Modifier
.fillMaxWidth() // 填充宽度
.fillMaxSize() // 填充整个空间
.width(100.dp) // 固定宽度
.height(50.dp) // 固定高度
.size(100.dp) // 固定宽高
.padding(16.dp) // 内边距
.padding(horizontal = 8.dp) // 水平内边距
.background(Color.Red) // 背景色
.border(1.dp, Color.Gray) // 边框
.clip(RoundedCornerShape(8.dp)) // 圆角
.clickable { } // 点击
3. Flutter 速查表¶
基础组件¶
Dart
// 文本
Text('Hello', style: TextStyle(fontSize: 20, color: Colors.red))
// 按钮
ElevatedButton(onPressed: () {}, child: Text('Click'))
TextButton(onPressed: () {}, child: Text('Text'))
OutlinedButton(onPressed: () {}, child: Text('Outlined'))
IconButton(onPressed: () {}, icon: Icon(Icons.add))
// 图片
Image.network('https://example.com/image.png')
Image.asset('assets/images/logo.png')
// 输入框
TextField(
decoration: InputDecoration(labelText: 'Label'),
onChanged: (value) {},
)
布局¶
Dart
// Column - 垂直
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [Text('A'), Text('B')],
)
// Row - 水平
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [Text('Left'), Text('Right')],
)
// Stack - 层叠
Stack(
children: [
Image.network('bg.jpg'),
Positioned(bottom: 16, child: Text('Overlay')),
],
)
// ListView
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) => ListTile(title: Text(items[index])),
)
状态管理¶
Dart
// StatefulWidget
class Counter extends StatefulWidget {
@override
_CounterState createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int count = 0;
void increment() {
setState(() => count++);
}
@override
Widget build(BuildContext context) {
return Text('$count');
}
}
// Provider
class CounterModel extends ChangeNotifier {
int count = 0;
void increment() {
count++;
notifyListeners();
}
}
// 使用
Consumer<CounterModel>(
builder: (context, counter, child) => Text('${counter.count}'),
)
4. Gradle 速查表¶
常用命令¶
Bash
# 构建
./gradlew build # 完整构建
./gradlew assembleDebug # 构建Debug APK
./gradlew assembleRelease # 构建Release APK
./gradlew bundleRelease # 构建AAB
# 测试
./gradlew test # 运行单元测试
./gradlew connectedAndroidTest # 运行仪器测试
./gradlew testDebugUnitTest # 运行Debug单元测试
# 清理
./gradlew clean # 清理构建产物
./gradlew cleanBuildCache # 清理构建缓存
# 依赖
./gradlew dependencies # 查看依赖树
./gradlew app:dependencies # 查看app模块依赖
# 其他
./gradlew tasks # 查看所有任务
./gradlew lint # 运行静态检查
./gradlew --stop # 停止Gradle Daemon
配置片段¶
Kotlin
// 依赖配置
dependencies {
implementation("androidx.core:core-ktx:1.13.1")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
}
// 版本管理
android {
compileSdk = 35
defaultConfig {
minSdk = 24
targetSdk = 35
versionCode = 1
versionName = "1.0.0"
}
}
5. Git 速查表¶
常用命令¶
Bash
# 基础操作
git init # 初始化仓库
git clone <url> # 克隆仓库
git status # 查看状态
git add <file> # 添加文件
git add . # 添加所有文件
git commit -m "message" # 提交
git push # 推送到远程
git pull # 拉取更新
# 分支操作
git branch # 查看分支
git branch <name> # 创建分支
git checkout <branch> # 切换分支
git checkout -b <branch> # 创建并切换
git merge <branch> # 合并分支
git branch -d <branch> # 删除分支
# 查看历史
git log # 查看提交历史
git log --oneline # 简洁显示
git log --graph # 图形显示
git diff # 查看修改
# 撤销操作
git restore <file> # 撤销修改
git reset HEAD <file> # 取消暂存
git reset --hard HEAD~1 # 回退到上一个提交
# 标签
git tag <tagname> # 创建标签
git push origin <tagname> # 推送标签
6. 常用快捷键¶
VS Code¶
| 快捷键 | 功能 |
|---|---|
Ctrl+P | 快速打开文件 |
Ctrl+Shift+P | 命令面板 |
Ctrl+Shift+F | 全局搜索 |
Ctrl+Shift+G | 源代码管理 |
Ctrl+Shift+E | 资源管理器 |
Ctrl+Shift+X | 扩展 |
F5 | 启动调试 |
Ctrl+Shift+A | 构建APK |
Android Studio¶
| 快捷键 | 功能 |
|---|---|
Ctrl+N | 查找类 |
Ctrl+Shift+N | 查找文件 |
Ctrl+Alt+L | 格式化代码 |
Ctrl+Shift+A | 查找操作 |
Shift+F10 | 运行 |
Shift+F9 | 调试 |
Ctrl+Shift+F8 | 查看断点 |