添加代码 (add)
add 命令用于在现有项目中生成各种代码文件,包括页面、组件、ViewModel、服务、模型和模块。
提示:为确保生成代码与最新模板/基础库一致,建议在生成前执行
flu-cli update-templates --force。
基本用法
bash
flu-cli add <type> <name> [options]
# 简写
flu-cli a <type> <name> [options]
# 查看支持的类型列表
flu-cli add --list
flu-cli a --list查看支持的类型
使用 --list 选项查看所有支持的组件类型及其详细信息:
bash
flu-cli add --list这将显示:
- 📦 所有支持的组件类型
- 🎯 每种类型的详细说明
- ⚡ 可用的选项
- 💡 使用示例
- 🚀 快速开始指南
支持的类型
| 类型 | 表情 | 别名 | 说明 |
|---|---|---|---|
page | 📄 | - | 页面组件 (Page + ViewModel) |
widget | 🧩 | - | 通用组件 |
component | 🔧 | - | 业务组件 |
viewmodel | 🎮 | vm | 视图模型 |
service | ⚙️ | - | 服务层 (API、存储、认证等) |
model | 📊 | - | 数据模型 |
module | 📦 | - | 完整功能模块 |
通用参数
| 参数 | 简写 | 说明 |
|---|---|---|
--list | - | 查看支持的类型列表 |
--feature | -f | 所属功能模块(Modular/Clean 模板) |
添加页面 (page)
创建页面文件和对应的 ViewModel。
用法
bash
flu-cli add page <name> [options]
flu-cli a page <name> [options]参数
| 参数 | 说明 |
|---|---|
--stateful | 创建 StatefulWidget(默认 StatelessWidget) |
--stateless | 强制创建 StatelessWidget(即使有 ViewModel,不推荐) |
--no-vm | 不生成 ViewModel |
-f, --feature | 所属功能模块 |
示例
创建基础页面
bash
flu-cli a page home生成文件(Lite 模板):
lib/
├── pages/
│ └── home_page.dart
└── viewmodels/
└── home_viewmodel.dart创建 StatefulWidget 页面
bash
flu-cli a page home --stateful生成 StatefulWidget 而不是 StatelessWidget。
不生成 ViewModel
bash
flu-cli a page home --no-vm只生成页面文件,不生成 ViewModel。
在功能模块中创建
bash
flu-cli a page user_list -f user生成文件(Modular/Clean 模板):
lib/features/user/
├── pages/
│ └── user_list_page.dart
└── viewmodels/
└── user_list_viewmodel.dart生成的代码
StatelessWidget(默认)
dart
import 'package:flutter/material.dart';
import '../viewmodels/home_viewmodel.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
final viewModel = HomeViewModel();
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
),
body: const Center(
child: Text('Home Page'),
),
);
}
}StatefulWidget
dart
import 'package:flutter/material.dart';
import '../viewmodels/home_viewmodel.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late final HomeViewModel _viewModel;
@override
void initState() {
super.initState();
_viewModel = HomeViewModel();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
),
body: const Center(
child: Text('Home Page'),
),
);
}
@override
void dispose() {
_viewModel.dispose();
super.dispose();
}
}添加组件 (widget)
创建可复用的 Widget 组件。
用法
bash
flu-cli add widget <name> [options]
flu-cli a widget <name> [options]参数
| 参数 | 说明 |
|---|---|
--stateful | 创建 StatefulWidget |
-f, --feature | 所属功能模块 |
示例
bash
# 创建 Widget
flu-cli a widget custom_button
# 创建 StatefulWidget
flu-cli a widget animated_card --stateful
# 在功能模块中创建
flu-cli a widget user_card -f user生成文件
lib/
└── widgets/
└── custom_button_widget.dart添加复合组件 (component)
创建包含多个 Widget 的复合组件。
用法
bash
flu-cli add component <name> [options]
flu-cli a component <name> [options]示例
bash
# 创建 Component
flu-cli a component user_card
# 在功能模块中创建
flu-cli a component product_list -f shop生成文件
lib/
└── components/
└── user_card_component.dart添加 ViewModel (viewmodel)
创建视图模型,管理页面状态和业务逻辑。
用法
bash
flu-cli add viewmodel <name> [options]
flu-cli add vm <name> [options]
flu-cli a vm <name> [options]示例
bash
# 创建 ViewModel
flu-cli a vm home
# 在功能模块中创建
flu-cli a vm user_list -f user生成文件
lib/
└── viewmodels/
└── home_viewmodel.dart生成的代码
dart
import 'package:flutter/foundation.dart';
class HomeViewModel extends ChangeNotifier {
// 状态
bool _isLoading = false;
bool get isLoading => _isLoading;
// 初始化
HomeViewModel() {
_init();
}
void _init() {
// 初始化逻辑
}
// 业务方法
Future<void> loadData() async {
_isLoading = true;
notifyListeners();
try {
// 加载数据
await Future.delayed(const Duration(seconds: 1));
} catch (e) {
debugPrint('Error: $e');
} finally {
_isLoading = false;
notifyListeners();
}
}
@override
void dispose() {
// 清理资源
super.dispose();
}
}添加服务 (service)
创建业务服务,处理 API 调用、数据存储等。
用法
bash
flu-cli add service <name> [options]
flu-cli a service <name> [options]参数
| 参数 | 说明 |
|---|---|
--type | 服务类型: api, storage, auth(默认: api) |
-f, --feature | 所属功能模块 |
示例
API Service
bash
flu-cli a service user --type api生成 API 服务,包含 HTTP 请求方法。
依赖提示:
ℹ 请添加依赖: http: ^1.1.0Storage Service
bash
flu-cli a service cache --type storage生成本地存储服务。
依赖提示:
ℹ 请添加依赖: shared_preferences: ^2.2.0Auth Service
bash
flu-cli a service auth --type auth生成认证服务。
依赖提示:
ℹ 请添加依赖: shared_preferences: ^2.2.0在功能模块中创建
bash
flu-cli a service product -f shop --type api生成文件
lib/
└── services/
└── user_service.dart生成的代码
API Service
dart
import 'dart:convert';
import 'package:http/http.dart' as http;
class UserService {
static const String baseUrl = 'https://api.example.com';
// GET 请求
Future<dynamic> getUsers() async {
try {
final response = await http.get(
Uri.parse('$baseUrl/users'),
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to load users');
}
} catch (e) {
throw Exception('Error: $e');
}
}
// POST 请求
Future<dynamic> createUser(Map<String, dynamic> data) async {
try {
final response = await http.post(
Uri.parse('$baseUrl/users'),
headers: {'Content-Type': 'application/json'},
body: json.encode(data),
);
if (response.statusCode == 201) {
return json.decode(response.body);
} else {
throw Exception('Failed to create user');
}
} catch (e) {
throw Exception('Error: $e');
}
}
}添加模型 (model)
创建数据模型类。
用法
bash
flu-cli add model <name> [options]
flu-cli a model <name> [options]参数
| 参数 | 说明 |
|---|---|
--json <file> | 从 JSON 文件生成 |
-f, --feature | 所属功能模块 |
示例
创建基础模型
bash
flu-cli a model user从 JSON 生成
创建 JSON 文件:
bash
echo '{
"id": "1",
"name": "John Doe",
"email": "john@example.com",
"age": 30,
"is_active": true,
"tags": ["flutter", "dart"]
}' > user.json从 JSON 生成模型:
bash
flu-cli a model user --json user.jsonflu-cli 会自动推断类型:
"1"→String30→inttrue→bool["flutter"]→List<String>
在功能模块中创建
bash
flu-cli a model product -f shop生成文件
lib/
└── models/
└── user_model.dart生成的代码
dart
class User {
final String id;
final String name;
final String email;
final int age;
final bool isActive;
final List<String> tags;
User({
required this.id,
required this.name,
required this.email,
required this.age,
required this.isActive,
required this.tags,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as String,
name: json['name'] as String,
email: json['email'] as String,
age: json['age'] as int,
isActive: json['is_active'] as bool,
tags: (json['tags'] as List<dynamic>).cast<String>(),
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'email': email,
'age': age,
'is_active': isActive,
'tags': tags,
};
}
}创建模块 (module)
创建完整的功能模块结构。
用法
bash
flu-cli add module <name>
flu-cli a module <name>示例
bash
flu-cli a module user生成结构
lib/features/user/
├── pages/
│ └── index.dart
├── viewmodels/
│ └── index.dart
├── widgets/
│ └── index.dart
├── services/
│ └── index.dart
├── models/
│ └── index.dart
└── index.dart每个 index.dart 文件用于导出该目录下的所有文件。
使用模块
创建模块后,可以在模块中添加代码:
bash
# 添加页面
flu-cli a page user_list -f user
# 添加服务
flu-cli a service user -f user --type api
# 添加模型
flu-cli a model user -f user自动更新 index.dart
生成代码时,flu-cli 会自动更新对应的 index.dart 文件:
dart
// lib/pages/index.dart
export 'home_page.dart';
export 'user_list_page.dart';
export 'user_detail_page.dart';这样可以方便地导入:
dart
import 'package:my_app/pages/index.dart';工作目录
重要: 始终在项目根目录执行命令。
bash
# ✅ 正确
cd my_app
flu-cli a page home
# ❌ 错误
cd my_app/lib
flu-cli a page home # 会在 lib/lib/pages/ 下生成命名规范
文件命名
- 使用 snake_case
- 添加类型后缀
bash
flu-cli a page user_list # user_list_page.dart
flu-cli a widget custom_button # custom_button_widget.dart
flu-cli a service api # api_service.dart
flu-cli a model user # user_model.dart类命名
- 使用 PascalCase
- 添加类型后缀
dart
class UserListPage extends StatelessWidget { }
class CustomButtonWidget extends StatelessWidget { }
class ApiService { }
class UserModel { }常见问题
如何覆盖已存在的文件?
flu-cli 不会覆盖已存在的文件,会提示文件已存在。如需重新生成,请先删除文件。
如何自定义生成的代码?
使用 VSCode 片段驱动生成。
生成的文件在哪里?
- Lite 模板:
lib/pages/,lib/widgets/等 - Modular/Clean 模板:
lib/features/<module>/pages/等
如何查看生成的文件列表?
生成成功后,flu-cli 会显示生成的文件路径。