sdd-full 4.6.2 → 4.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin.js +1 -1
- package/index.js +18 -12
- package/package.json +1 -1
- package/skills/VERSION.md +3 -3
- package/skills/design-planning/global-overlay-stack-standard/SKILL.md +83 -0
- package/skills/design-planning/ui-motion-interaction-standard/SKILL.md +79 -0
- package/skills/flutter/skills/flutter-add-integration-test/SKILL.md +165 -0
- package/skills/flutter/skills/flutter-add-widget-preview/SKILL.md +147 -0
- package/skills/flutter/skills/flutter-add-widget-test/SKILL.md +156 -0
- package/skills/flutter/skills/flutter-apply-architecture-best-practices/SKILL.md +164 -0
- package/skills/flutter/skills/flutter-build-responsive-layout/SKILL.md +141 -0
- package/skills/flutter/skills/flutter-fix-layout-issues/SKILL.md +132 -0
- package/skills/flutter/skills/flutter-implement-json-serialization/SKILL.md +155 -0
- package/skills/flutter/skills/flutter-setup-declarative-routing/SKILL.md +257 -0
- package/skills/flutter/skills/flutter-setup-localization/SKILL.md +212 -0
- package/skills/flutter/skills/flutter-use-http-package/SKILL.md +177 -0
- package/skills/requirement-analysis/sdd/mock_sdd.md +156 -0
- package/skills/writing-skills/SKILL.md +654 -0
- package/skills/writing-skills/anthropic-best-practices.md +1149 -0
- package/skills/writing-skills/examples/CLAUDE_MD_TESTING.md +189 -0
- package/skills/writing-skills/graphviz-conventions.dot +172 -0
- package/skills/writing-skills/persuasion-principles.md +187 -0
- package/skills/writing-skills/render-graphs.js +168 -0
- package/skills/writing-skills/testing-skills-with-subagents.md +384 -0
- package/skills/checklist.md +0 -154
- package/skills//345/256/214/346/225/264/345/274/200/345/217/221/346/265/201/347/250/213/346/211/213/345/206/214.md +0 -454
- package/skills//346/212/200/350/203/275/344/275/223/347/263/273/345/256/214/345/226/204/345/273/272/350/256/256.md +0 -308
- package/skills//346/212/200/350/203/275/344/275/277/347/224/250/346/214/207/345/215/227.md +0 -309
- package/skills//346/212/200/350/203/275/345/206/263/347/255/226/346/240/221.md +0 -338
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
【claude code调用标识:flutter-implement-json-serialization】【trae调用标识:flutter-implement-json-serialization+Flutter开发】【流程场景:1.完整3阶段SDD流程、3.小型功能迭代】
|
|
2
|
+
|
|
3
|
+
---
|
|
4
|
+
name: flutter-implement-json-serialization
|
|
5
|
+
description: Create model classes with `fromJson` and `toJson` methods using `dart:convert`. Use when manually mapping JSON keys to class properties for simple data structures.
|
|
6
|
+
metadata:
|
|
7
|
+
model: models/gemini-3.1-pro-preview
|
|
8
|
+
last_modified: Tue, 21 Apr 2026 21:44:50 GMT
|
|
9
|
+
---
|
|
10
|
+
# Serializing JSON Manually in Flutter
|
|
11
|
+
|
|
12
|
+
## Contents
|
|
13
|
+
- [Core Guidelines](#core-guidelines)
|
|
14
|
+
- [Workflow: Implementing a Serializable Model](#workflow-implementing-a-serializable-model)
|
|
15
|
+
- [Workflow: Fetching and Parsing JSON](#workflow-fetching-and-parsing-json)
|
|
16
|
+
- [Examples](#examples)
|
|
17
|
+
|
|
18
|
+
## Core Guidelines
|
|
19
|
+
|
|
20
|
+
- **Import `dart:convert`**: Utilize Flutter's built-in `dart:convert` library for manual JSON encoding (`jsonEncode`) and decoding (`jsonDecode`).
|
|
21
|
+
- **Enforce Type Safety**: Always cast the `dynamic` result of `jsonDecode()` to the expected type, typically `Map<String, dynamic>` for objects or `List<dynamic>` for arrays.
|
|
22
|
+
- **Encapsulate Serialization Logic**: Define plain model classes containing properties corresponding to the JSON structure. Implement a `fromJson` factory constructor and a `toJson` method within the model.
|
|
23
|
+
- **Handle Background Parsing**: If parsing large JSON documents (execution time > 16ms), offload the parsing logic to a separate isolate using Flutter's `compute()` function to prevent UI jank.
|
|
24
|
+
- **Throw Exceptions on Failure**: When handling HTTP responses, throw an exception if the status code is not successful (e.g., not 200 OK or 201 Created). Do not return `null`.
|
|
25
|
+
|
|
26
|
+
## Workflow: Implementing a Serializable Model
|
|
27
|
+
|
|
28
|
+
Use this checklist to implement manual JSON serialization for a data model.
|
|
29
|
+
|
|
30
|
+
**Task Progress:**
|
|
31
|
+
- [ ] Define the plain model class with `final` properties.
|
|
32
|
+
- [ ] Implement the `factory Model.fromJson(Map<String, dynamic> json)` constructor.
|
|
33
|
+
- [ ] Implement the `Map<String, dynamic> toJson()` method.
|
|
34
|
+
- [ ] Write unit tests for both serialization methods.
|
|
35
|
+
- [ ] Run validator -> review type mismatch errors -> fix casting logic.
|
|
36
|
+
|
|
37
|
+
1. **Define the Model**: Create a class with properties matching the JSON keys.
|
|
38
|
+
2. **Implement `fromJson`**: Extract values from the `Map` and cast them to the appropriate Dart types. Use pattern matching or explicit casting.
|
|
39
|
+
3. **Implement `toJson`**: Return a `Map<String, dynamic>` mapping the class properties back to their JSON string keys.
|
|
40
|
+
4. **Validate**: Execute unit tests to ensure type safety, autocompletion, and compile-time exception handling function correctly.
|
|
41
|
+
|
|
42
|
+
## Workflow: Fetching and Parsing JSON
|
|
43
|
+
|
|
44
|
+
Use this conditional workflow when retrieving and parsing JSON from a network request.
|
|
45
|
+
|
|
46
|
+
**Task Progress:**
|
|
47
|
+
- [ ] Execute the HTTP request.
|
|
48
|
+
- [ ] Validate the response status code.
|
|
49
|
+
- [ ] Determine parsing strategy (Synchronous vs. Isolate).
|
|
50
|
+
- [ ] Decode and map the JSON to the model.
|
|
51
|
+
|
|
52
|
+
1. **Execute Request**: Use the `http` package to perform the network call.
|
|
53
|
+
2. **Validate Response**:
|
|
54
|
+
- If `response.statusCode == 200` (or 201 for POST), proceed to parsing.
|
|
55
|
+
- If the status code indicates failure, throw an `Exception`.
|
|
56
|
+
3. **Determine Parsing Strategy**:
|
|
57
|
+
- If parsing a **small payload** (e.g., a single object), parse synchronously on the main thread.
|
|
58
|
+
- If parsing a **large payload** (e.g., an array of thousands of objects), use `compute(parseFunction, response.body)` to parse in a background isolate.
|
|
59
|
+
4. **Decode and Map**: Pass the decoded JSON to your model's `fromJson` constructor.
|
|
60
|
+
|
|
61
|
+
## Examples
|
|
62
|
+
|
|
63
|
+
### High-Fidelity Model Implementation
|
|
64
|
+
|
|
65
|
+
```dart
|
|
66
|
+
import 'dart:convert';
|
|
67
|
+
|
|
68
|
+
class User {
|
|
69
|
+
final int id;
|
|
70
|
+
final String name;
|
|
71
|
+
final String email;
|
|
72
|
+
|
|
73
|
+
const User({
|
|
74
|
+
required this.id,
|
|
75
|
+
required this.name,
|
|
76
|
+
required this.email,
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// Factory constructor for deserialization
|
|
80
|
+
factory User.fromJson(Map<String, dynamic> json) {
|
|
81
|
+
return switch (json) {
|
|
82
|
+
{
|
|
83
|
+
'id': int id,
|
|
84
|
+
'name': String name,
|
|
85
|
+
'email': String email,
|
|
86
|
+
} =>
|
|
87
|
+
User(
|
|
88
|
+
id: id,
|
|
89
|
+
name: name,
|
|
90
|
+
email: email,
|
|
91
|
+
),
|
|
92
|
+
_ => throw const FormatException('Failed to load User.'),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Method for serialization
|
|
97
|
+
Map<String, dynamic> toJson() {
|
|
98
|
+
return {
|
|
99
|
+
'id': id,
|
|
100
|
+
'name': name,
|
|
101
|
+
'email': email,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Synchronous Parsing (Small Payload)
|
|
108
|
+
|
|
109
|
+
```dart
|
|
110
|
+
import 'dart:convert';
|
|
111
|
+
import 'package:http/http.dart' as http;
|
|
112
|
+
|
|
113
|
+
Future<User> fetchUser(http.Client client, int userId) async {
|
|
114
|
+
final response = await client.get(
|
|
115
|
+
Uri.parse('https://api.example.com/users/$userId'),
|
|
116
|
+
headers: {'Accept': 'application/json'},
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
if (response.statusCode == 200) {
|
|
120
|
+
// Decode returns dynamic, cast to Map<String, dynamic>
|
|
121
|
+
final Map<String, dynamic> jsonMap = jsonDecode(response.body) as Map<String, dynamic>;
|
|
122
|
+
return User.fromJson(jsonMap);
|
|
123
|
+
} else {
|
|
124
|
+
throw Exception('Failed to load user');
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Background Parsing (Large Payload)
|
|
130
|
+
|
|
131
|
+
```dart
|
|
132
|
+
import 'dart:convert';
|
|
133
|
+
import 'package:flutter/foundation.dart';
|
|
134
|
+
import 'package:http/http.dart' as http;
|
|
135
|
+
|
|
136
|
+
// Top-level function required for compute()
|
|
137
|
+
List<User> parseUsers(String responseBody) {
|
|
138
|
+
final parsed = (jsonDecode(responseBody) as List<dynamic>).cast<Map<String, dynamic>>();
|
|
139
|
+
return parsed.map<User>((json) => User.fromJson(json)).toList();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
Future<List<User>> fetchUsers(http.Client client) async {
|
|
143
|
+
final response = await client.get(
|
|
144
|
+
Uri.parse('https://api.example.com/users'),
|
|
145
|
+
headers: {'Accept': 'application/json'},
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
if (response.statusCode == 200) {
|
|
149
|
+
// Offload expensive parsing to a background isolate
|
|
150
|
+
return compute(parseUsers, response.body);
|
|
151
|
+
} else {
|
|
152
|
+
throw Exception('Failed to load users');
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
【claude code调用标识:flutter-setup-declarative-routing】【trae调用标识:flutter-setup-declarative-routing+Flutter开发】【流程场景:1.完整3阶段SDD流程、2.从零开始新项目】
|
|
2
|
+
|
|
3
|
+
---
|
|
4
|
+
name: flutter-setup-declarative-routing
|
|
5
|
+
description: Configure `MaterialApp.router` using a package like `go_router` for advanced URL-based navigation. Use when developing web applications or mobile apps that require specific deep linking and browser history support.
|
|
6
|
+
metadata:
|
|
7
|
+
model: models/gemini-3.1-pro-preview
|
|
8
|
+
last_modified: Tue, 21 Apr 2026 21:08:03 GMT
|
|
9
|
+
---
|
|
10
|
+
# Implementing Routing and Deep Linking
|
|
11
|
+
|
|
12
|
+
## Contents
|
|
13
|
+
- [Core Concepts](#core-concepts)
|
|
14
|
+
- [Workflow: Initializing the Application and Router](#workflow-initializing-the-application-and-router)
|
|
15
|
+
- [Workflow: Configuring Platform Deep Linking](#workflow-configuring-platform-deep-linking)
|
|
16
|
+
- [Workflow: Implementing Nested Navigation](#workflow-implementing-nested-navigation)
|
|
17
|
+
- [Examples](#examples)
|
|
18
|
+
|
|
19
|
+
## Core Concepts
|
|
20
|
+
|
|
21
|
+
Use the `go_router` package for declarative routing in Flutter. It provides a robust API for complex routing scenarios, deep linking, and nested navigation.
|
|
22
|
+
|
|
23
|
+
- **GoRouter**: The central configuration object defining the application's route tree.
|
|
24
|
+
- **GoRoute**: A standard route mapping a URL path to a Flutter screen.
|
|
25
|
+
- **ShellRoute / StatefulShellRoute**: Wraps child routes in a persistent UI shell (e.g., a `BottomNavigationBar`). `StatefulShellRoute` maintains the state of parallel navigation branches.
|
|
26
|
+
- **Path URL Strategy**: Removes the default `#` fragment from web URLs, essential for clean deep linking across platforms.
|
|
27
|
+
|
|
28
|
+
## Workflow: Initializing the Application and Router
|
|
29
|
+
|
|
30
|
+
Follow this workflow to bootstrap a new Flutter application with `go_router` and configure the root routing mechanism.
|
|
31
|
+
|
|
32
|
+
### Task Progress
|
|
33
|
+
- [ ] Create the Flutter application.
|
|
34
|
+
- [ ] Add the `go_router` dependency.
|
|
35
|
+
- [ ] Configure the URL strategy for web/deep linking.
|
|
36
|
+
- [ ] Implement the `GoRouter` configuration.
|
|
37
|
+
- [ ] Bind the router to `MaterialApp.router`.
|
|
38
|
+
|
|
39
|
+
### 1. Scaffold the Application
|
|
40
|
+
Run the following commands to create the app and add the required routing package:
|
|
41
|
+
```bash
|
|
42
|
+
flutter create <app-name>
|
|
43
|
+
cd <app-name>
|
|
44
|
+
flutter pub add go_router
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### 2. Configure the Router
|
|
48
|
+
Define a top-level `GoRouter` instance. Handle authentication or state-based routing using the `redirect` parameter.
|
|
49
|
+
|
|
50
|
+
```dart
|
|
51
|
+
import 'package:flutter/material.dart';
|
|
52
|
+
import 'package:go_router/go_router.dart';
|
|
53
|
+
import 'package:flutter_web_plugins/url_strategy.dart';
|
|
54
|
+
|
|
55
|
+
void main() {
|
|
56
|
+
// Use path URL strategy to remove the '#' from web URLs
|
|
57
|
+
usePathUrlStrategy();
|
|
58
|
+
runApp(const MyApp());
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
final GoRouter _router = GoRouter(
|
|
62
|
+
initialLocation: '/',
|
|
63
|
+
routes: [
|
|
64
|
+
GoRoute(
|
|
65
|
+
path: '/',
|
|
66
|
+
builder: (context, state) => const HomeScreen(),
|
|
67
|
+
routes: [
|
|
68
|
+
GoRoute(
|
|
69
|
+
path: 'details/:id',
|
|
70
|
+
builder: (context, state) => DetailsScreen(id: state.pathParameters['id']!),
|
|
71
|
+
),
|
|
72
|
+
],
|
|
73
|
+
),
|
|
74
|
+
],
|
|
75
|
+
errorBuilder: (context, state) => ErrorScreen(error: state.error),
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
class MyApp extends StatelessWidget {
|
|
79
|
+
const MyApp({super.key});
|
|
80
|
+
|
|
81
|
+
@override
|
|
82
|
+
Widget build(BuildContext context) {
|
|
83
|
+
return MaterialApp.router(
|
|
84
|
+
routerConfig: _router,
|
|
85
|
+
title: 'Routing App',
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Workflow: Configuring Platform Deep Linking
|
|
92
|
+
|
|
93
|
+
Configure the native platforms to intercept specific URLs and route them into the Flutter application.
|
|
94
|
+
|
|
95
|
+
### Task Progress
|
|
96
|
+
- [ ] Determine target platforms (iOS, Android, or both).
|
|
97
|
+
- [ ] Apply conditional configuration for Android (Manifest + Asset Links).
|
|
98
|
+
- [ ] Apply conditional configuration for iOS (Plist + Entitlements + AASA).
|
|
99
|
+
- [ ] Run validator -> review errors -> fix.
|
|
100
|
+
|
|
101
|
+
### If configuring for Android:
|
|
102
|
+
1. **Modify `AndroidManifest.xml`**: Add the intent filter inside the `<activity>` tag for `.MainActivity`.
|
|
103
|
+
```xml
|
|
104
|
+
<intent-filter android:autoVerify="true">
|
|
105
|
+
<action android:name="android.intent.action.VIEW" />
|
|
106
|
+
<category android:name="android.intent.category.DEFAULT" />
|
|
107
|
+
<category android:name="android.intent.category.BROWSABLE" />
|
|
108
|
+
<data android:scheme="http" android:host="yourdomain.com" />
|
|
109
|
+
<data android:scheme="https" />
|
|
110
|
+
</intent-filter>
|
|
111
|
+
```
|
|
112
|
+
2. **Host `assetlinks.json`**: Serve the following JSON at `https://yourdomain.com/.well-known/assetlinks.json`.
|
|
113
|
+
```json
|
|
114
|
+
[{
|
|
115
|
+
"relation": ["delegate_permission/common.handle_all_urls"],
|
|
116
|
+
"target": {
|
|
117
|
+
"namespace": "android_app",
|
|
118
|
+
"package_name": "com.yourcompany.yourapp",
|
|
119
|
+
"sha256_cert_fingerprints": ["YOUR_SHA256_FINGERPRINT"]
|
|
120
|
+
}
|
|
121
|
+
}]
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### If configuring for iOS:
|
|
125
|
+
1. **Modify `Info.plist`**: Opt-in to Flutter's default deep link handler.
|
|
126
|
+
*Note: If using a third-party deep linking plugin (e.g., `app_links`), set this to `NO` to prevent conflicts.*
|
|
127
|
+
```xml
|
|
128
|
+
<key>FlutterDeepLinkingEnabled</key>
|
|
129
|
+
<true/>
|
|
130
|
+
```
|
|
131
|
+
2. **Modify `Runner.entitlements`**: Add the associated domain.
|
|
132
|
+
```xml
|
|
133
|
+
<key>com.apple.developer.associated-domains</key>
|
|
134
|
+
<array>
|
|
135
|
+
<string>applinks:yourdomain.com</string>
|
|
136
|
+
</array>
|
|
137
|
+
```
|
|
138
|
+
3. **Host `apple-app-site-association`**: Serve the following JSON (without a `.json` extension) at `https://yourdomain.com/.well-known/apple-app-site-association`.
|
|
139
|
+
```json
|
|
140
|
+
{
|
|
141
|
+
"applinks": {
|
|
142
|
+
"apps": [],
|
|
143
|
+
"details": [{
|
|
144
|
+
"appIDs": ["TEAM_ID.com.yourcompany.yourapp"],
|
|
145
|
+
"paths": ["*"],
|
|
146
|
+
"components": [{"/": "/*"}]
|
|
147
|
+
}]
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Validation Loop
|
|
153
|
+
Run validator -> review errors -> fix.
|
|
154
|
+
- **Android**: Test using ADB.
|
|
155
|
+
```bash
|
|
156
|
+
adb shell 'am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "https://yourdomain.com/details/123"' com.yourcompany.yourapp
|
|
157
|
+
```
|
|
158
|
+
- **iOS**: Test using `xcrun` on a booted simulator.
|
|
159
|
+
```bash
|
|
160
|
+
xcrun simctl openurl booted https://yourdomain.com/details/123
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Workflow: Implementing Nested Navigation
|
|
164
|
+
|
|
165
|
+
Use `StatefulShellRoute` to implement persistent UI shells (like a bottom navigation bar) that maintain the state of their child routes.
|
|
166
|
+
|
|
167
|
+
### Task Progress
|
|
168
|
+
- [ ] Define `StatefulShellRoute.indexedStack` in the `GoRouter` configuration.
|
|
169
|
+
- [ ] Create `StatefulShellBranch` instances for each navigation tab.
|
|
170
|
+
- [ ] Implement the shell widget using `StatefulNavigationShell`.
|
|
171
|
+
|
|
172
|
+
```dart
|
|
173
|
+
final GoRouter _router = GoRouter(
|
|
174
|
+
initialLocation: '/home',
|
|
175
|
+
routes: [
|
|
176
|
+
StatefulShellRoute.indexedStack(
|
|
177
|
+
builder: (context, state, navigationShell) {
|
|
178
|
+
return ScaffoldWithNavBar(navigationShell: navigationShell);
|
|
179
|
+
},
|
|
180
|
+
branches: [
|
|
181
|
+
StatefulShellBranch(
|
|
182
|
+
routes: [
|
|
183
|
+
GoRoute(
|
|
184
|
+
path: '/home',
|
|
185
|
+
builder: (context, state) => const HomeScreen(),
|
|
186
|
+
),
|
|
187
|
+
],
|
|
188
|
+
),
|
|
189
|
+
StatefulShellBranch(
|
|
190
|
+
routes: [
|
|
191
|
+
GoRoute(
|
|
192
|
+
path: '/settings',
|
|
193
|
+
builder: (context, state) => const SettingsScreen(),
|
|
194
|
+
),
|
|
195
|
+
],
|
|
196
|
+
),
|
|
197
|
+
],
|
|
198
|
+
),
|
|
199
|
+
],
|
|
200
|
+
);
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
## Examples
|
|
204
|
+
|
|
205
|
+
### High-Fidelity Shell Widget Implementation
|
|
206
|
+
Implement the UI shell that consumes the `StatefulNavigationShell` to handle branch switching.
|
|
207
|
+
|
|
208
|
+
```dart
|
|
209
|
+
class ScaffoldWithNavBar extends StatelessWidget {
|
|
210
|
+
const ScaffoldWithNavBar({
|
|
211
|
+
required this.navigationShell,
|
|
212
|
+
super.key,
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
final StatefulNavigationShell navigationShell;
|
|
216
|
+
|
|
217
|
+
void _goBranch(int index) {
|
|
218
|
+
navigationShell.goBranch(
|
|
219
|
+
index,
|
|
220
|
+
// Support navigating to the initial location when tapping the active tab.
|
|
221
|
+
initialLocation: index == navigationShell.currentIndex,
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
@override
|
|
226
|
+
Widget build(BuildContext context) {
|
|
227
|
+
return Scaffold(
|
|
228
|
+
body: navigationShell,
|
|
229
|
+
bottomNavigationBar: NavigationBar(
|
|
230
|
+
selectedIndex: navigationShell.currentIndex,
|
|
231
|
+
onDestinationSelected: _goBranch,
|
|
232
|
+
destinations: const [
|
|
233
|
+
NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
|
|
234
|
+
NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
|
|
235
|
+
],
|
|
236
|
+
),
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### Programmatic Navigation
|
|
243
|
+
Use the `context.go()` and `context.push()` extension methods provided by `go_router`.
|
|
244
|
+
|
|
245
|
+
```dart
|
|
246
|
+
// Replaces the current route stack with the target route (Declarative)
|
|
247
|
+
context.go('/details/123');
|
|
248
|
+
|
|
249
|
+
// Pushes the target route onto the existing stack (Imperative)
|
|
250
|
+
context.push('/details/123');
|
|
251
|
+
|
|
252
|
+
// Navigates using a named route and path parameters
|
|
253
|
+
context.goNamed('details', pathParameters: {'id': '123'});
|
|
254
|
+
|
|
255
|
+
// Pops the current route
|
|
256
|
+
context.pop();
|
|
257
|
+
```
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
【claude code调用标识:flutter-setup-localization】【trae调用标识:flutter-setup-localization+Flutter开发】【流程场景:1.完整3阶段SDD流程、3.小型功能迭代】
|
|
2
|
+
|
|
3
|
+
---
|
|
4
|
+
name: flutter-setup-localization
|
|
5
|
+
description: Add `flutter_localizations` and `intl` dependencies, enable "generate true" in `pubspec.yaml`, and create an `l10n.yaml` configuration file. Use when initializing localization support for a new Flutter project.
|
|
6
|
+
metadata:
|
|
7
|
+
model: models/gemini-3.1-pro-preview
|
|
8
|
+
last_modified: Tue, 21 Apr 2026 21:27:35 GMT
|
|
9
|
+
---
|
|
10
|
+
# Internationalizing Flutter Applications
|
|
11
|
+
|
|
12
|
+
## Contents
|
|
13
|
+
- [Core Concepts](#core-concepts)
|
|
14
|
+
- [Setup Workflow](#setup-workflow)
|
|
15
|
+
- [Implementation Workflow](#implementation-workflow)
|
|
16
|
+
- [Advanced Formatting](#advanced-formatting)
|
|
17
|
+
- [Examples](#examples)
|
|
18
|
+
|
|
19
|
+
## Core Concepts
|
|
20
|
+
Flutter handles internationalization (i18n) and localization (l10n) via the `flutter_localizations` and `intl` packages. The standard approach uses App Resource Bundle (`.arb`) files to define localized strings, which are then compiled into a generated `AppLocalizations` class for type-safe access within the widget tree.
|
|
21
|
+
|
|
22
|
+
## Setup Workflow
|
|
23
|
+
|
|
24
|
+
Copy and track this checklist when initializing internationalization in a Flutter project:
|
|
25
|
+
|
|
26
|
+
- [ ] **Task Progress**
|
|
27
|
+
- [ ] 1. Add dependencies to `pubspec.yaml`.
|
|
28
|
+
- [ ] 2. Enable the `generate` flag.
|
|
29
|
+
- [ ] 3. Create the `l10n.yaml` configuration file.
|
|
30
|
+
- [ ] 4. Configure `MaterialApp` or `CupertinoApp`.
|
|
31
|
+
|
|
32
|
+
### 1. Add Dependencies
|
|
33
|
+
Add the required localization packages to the project. Execute the following commands in the terminal:
|
|
34
|
+
```bash
|
|
35
|
+
flutter pub add flutter_localizations --sdk=flutter
|
|
36
|
+
flutter pub add intl:any
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Verify your `pubspec.yaml` includes the following under `dependencies`:
|
|
40
|
+
```yaml
|
|
41
|
+
dependencies:
|
|
42
|
+
flutter:
|
|
43
|
+
sdk: flutter
|
|
44
|
+
flutter_localizations:
|
|
45
|
+
sdk: flutter
|
|
46
|
+
intl: any
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### 2. Enable Code Generation
|
|
50
|
+
Open `pubspec.yaml` and enable the `generate` flag within the `flutter` section to automate localization tasks:
|
|
51
|
+
```yaml
|
|
52
|
+
flutter:
|
|
53
|
+
generate: true
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### 3. Create Configuration File
|
|
57
|
+
Create a new file named `l10n.yaml` in the root directory of the Flutter project. Define the input directory, template file, and output file:
|
|
58
|
+
```yaml
|
|
59
|
+
arb-dir: lib/l10n
|
|
60
|
+
template-arb-file: app_en.arb
|
|
61
|
+
output-localization-file: app_localizations.dart
|
|
62
|
+
synthetic-package: true
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### 4. Configure the App Entry Point
|
|
66
|
+
Import the generated localizations and the `flutter_localizations` library in your `main.dart`. Inject the delegates and supported locales into your `MaterialApp` or `CupertinoApp`.
|
|
67
|
+
|
|
68
|
+
```dart
|
|
69
|
+
import 'package:flutter_localizations/flutter_localizations.dart';
|
|
70
|
+
import 'package:flutter_gen/gen_l10n/app_localizations.dart'; // Adjust path if synthetic-package is false
|
|
71
|
+
|
|
72
|
+
// ... inside build method
|
|
73
|
+
return MaterialApp(
|
|
74
|
+
localizationsDelegates: const [
|
|
75
|
+
AppLocalizations.delegate,
|
|
76
|
+
GlobalMaterialLocalizations.delegate,
|
|
77
|
+
GlobalWidgetsLocalizations.delegate,
|
|
78
|
+
GlobalCupertinoLocalizations.delegate,
|
|
79
|
+
],
|
|
80
|
+
supportedLocales: const [
|
|
81
|
+
Locale('en'), // English
|
|
82
|
+
Locale('es'), // Spanish
|
|
83
|
+
],
|
|
84
|
+
home: const MyHomePage(),
|
|
85
|
+
);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Implementation Workflow
|
|
89
|
+
|
|
90
|
+
Follow this workflow when adding or modifying localized content.
|
|
91
|
+
|
|
92
|
+
### 1. Define ARB Files
|
|
93
|
+
* **If creating NEW content:** Add the base string to the template file (`lib/l10n/app_en.arb`). Include a description for context.
|
|
94
|
+
* **If EDITING existing content:** Locate the key in all supported `.arb` files and update the values.
|
|
95
|
+
|
|
96
|
+
```json
|
|
97
|
+
{
|
|
98
|
+
"helloWorld": "Hello World!",
|
|
99
|
+
"@helloWorld": {
|
|
100
|
+
"description": "The conventional newborn programmer greeting"
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Create corresponding files for other locales (e.g., `app_es.arb`):
|
|
106
|
+
```json
|
|
107
|
+
{
|
|
108
|
+
"helloWorld": "¡Hola Mundo!"
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### 2. Generate Localization Classes
|
|
113
|
+
Run the following command to trigger code generation:
|
|
114
|
+
```bash
|
|
115
|
+
flutter pub get
|
|
116
|
+
```
|
|
117
|
+
*Feedback Loop:* Run validator -> review terminal output for ARB syntax errors -> fix missing commas or mismatched placeholders -> re-run `flutter pub get`.
|
|
118
|
+
|
|
119
|
+
### 3. Consume Localized Strings
|
|
120
|
+
Access the localized strings in your widget tree using `AppLocalizations.of(context)`. Ensure the widget calling this is a descendant of `MaterialApp`.
|
|
121
|
+
|
|
122
|
+
```dart
|
|
123
|
+
Text(AppLocalizations.of(context)!.helloWorld)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## Advanced Formatting
|
|
127
|
+
|
|
128
|
+
Use placeholders for dynamic data, plurals, and conditional selects.
|
|
129
|
+
|
|
130
|
+
### Placeholders
|
|
131
|
+
Define parameters within curly braces and specify their type in the metadata object.
|
|
132
|
+
```json
|
|
133
|
+
"hello": "Hello {userName}",
|
|
134
|
+
"@hello": {
|
|
135
|
+
"description": "A message with a single parameter",
|
|
136
|
+
"placeholders": {
|
|
137
|
+
"userName": {
|
|
138
|
+
"type": "String",
|
|
139
|
+
"example": "Bob"
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Plurals
|
|
146
|
+
Use the `plural` syntax to handle quantity-based string variations. The `other` case is mandatory.
|
|
147
|
+
```json
|
|
148
|
+
"nWombats": "{count, plural, =0{no wombats} =1{1 wombat} other{{count} wombats}}",
|
|
149
|
+
"@nWombats": {
|
|
150
|
+
"description": "A plural message",
|
|
151
|
+
"placeholders": {
|
|
152
|
+
"count": {
|
|
153
|
+
"type": "num",
|
|
154
|
+
"format": "compact"
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Selects
|
|
161
|
+
Use the `select` syntax for conditional strings, such as gendered text.
|
|
162
|
+
```json
|
|
163
|
+
"pronoun": "{gender, select, male{he} female{she} other{they}}",
|
|
164
|
+
"@pronoun": {
|
|
165
|
+
"description": "A gendered message",
|
|
166
|
+
"placeholders": {
|
|
167
|
+
"gender": {
|
|
168
|
+
"type": "String"
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
## Examples
|
|
175
|
+
|
|
176
|
+
### Complete `l10n.yaml`
|
|
177
|
+
```yaml
|
|
178
|
+
arb-dir: lib/l10n
|
|
179
|
+
template-arb-file: app_en.arb
|
|
180
|
+
output-localization-file: app_localizations.dart
|
|
181
|
+
synthetic-package: true
|
|
182
|
+
use-escaping: true
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Complete Widget Implementation
|
|
186
|
+
```dart
|
|
187
|
+
import 'package:flutter/material.dart';
|
|
188
|
+
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
|
|
189
|
+
|
|
190
|
+
class GreetingWidget extends StatelessWidget {
|
|
191
|
+
final String userName;
|
|
192
|
+
final int notificationCount;
|
|
193
|
+
|
|
194
|
+
const GreetingWidget({
|
|
195
|
+
super.key,
|
|
196
|
+
required this.userName,
|
|
197
|
+
required this.notificationCount,
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
@override
|
|
201
|
+
Widget build(BuildContext context) {
|
|
202
|
+
final l10n = AppLocalizations.of(context)!;
|
|
203
|
+
|
|
204
|
+
return Column(
|
|
205
|
+
children: [
|
|
206
|
+
Text(l10n.hello(userName)),
|
|
207
|
+
Text(l10n.nWombats(notificationCount)),
|
|
208
|
+
],
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
```
|