@bdayadev/flutter-ultra-mcp 1.11.7 → 1.13.0

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.
@@ -0,0 +1,189 @@
1
+ ---
2
+ name: use-http-package
3
+ description: Use the `http` package to execute GET, POST, PUT, or DELETE requests. Use when you need to fetch from or send data to a REST API.
4
+ last_modified: Tue, 21 Apr 2026 21:36:42 GMT
5
+ ---
6
+
7
+ # Implementing Flutter Networking
8
+
9
+ ## Contents
10
+
11
+ - [Configuration & Permissions](#configuration--permissions)
12
+ - [Request Execution & Response Handling](#request-execution--response-handling)
13
+ - [Background Parsing](#background-parsing)
14
+ - [Workflow: Executing Network Operations](#workflow-executing-network-operations)
15
+ - [Examples](#examples)
16
+
17
+ ## Configuration & Permissions
18
+
19
+ Configure the environment and platform-specific permissions required for network access.
20
+
21
+ 1. Add the `http` package dependency via the terminal:
22
+ ```bash
23
+ flutter pub add http
24
+ ```
25
+ 2. Import the package in your Dart files:
26
+ ```dart
27
+ import 'package:http/http.dart' as http;
28
+ ```
29
+ 3. Configure Android permissions by adding the Internet permission to `android/app/src/main/AndroidManifest.xml`:
30
+ ```xml
31
+ <uses-permission android:name="android.permission.INTERNET" />
32
+ ```
33
+ 4. Configure macOS entitlements by adding the network client key to both `macos/Runner/DebugProfile.entitlements` and `macos/Runner/Release.entitlements`:
34
+ ```xml
35
+ <key>com.apple.security.network.client</key>
36
+ <true/>
37
+ ```
38
+
39
+ ## Request Execution & Response Handling
40
+
41
+ Execute HTTP operations and map responses to strongly typed Dart objects.
42
+
43
+ - **URIs:** Always parse URL strings using `Uri.parse('your_url')`.
44
+ - **Headers:** Inject authorization and content-type headers via the `headers` parameter map. Use `HttpHeaders.authorizationHeader` for auth tokens.
45
+ - **Payloads:** For POST and PUT requests, encode the body using `jsonEncode()` from `dart:convert`.
46
+ - **Status Validation:** Evaluate `response.statusCode`. Treat `200 OK` (GET/PUT/DELETE) and `201 CREATED` (POST) as success.
47
+ - **Error Handling:** Throw explicit exceptions for non-success status codes. Never return `null` on failure, as this prevents `FutureBuilder` from triggering its error state and causes infinite loading indicators.
48
+ - **Deserialization:** Parse the raw string using `jsonDecode(response.body)` and map it to a custom Dart object using a factory constructor (e.g., `fromJson`).
49
+
50
+ ## Background Parsing
51
+
52
+ Offload expensive JSON parsing to a separate Isolate to prevent UI jank (frame drops).
53
+
54
+ - Import `package:flutter/foundation.dart`.
55
+ - Use the `compute()` function to run the parsing logic in a background isolate.
56
+ - Ensure the parsing function passed to `compute()` is a top-level function or a static method, as closures or instance methods cannot be passed across isolates.
57
+
58
+ ## Workflow: Executing Network Operations
59
+
60
+ Use the following checklist to implement and validate network operations.
61
+
62
+ **Task Progress:**
63
+
64
+ - [ ] 1. Define the strongly typed Dart model with a `fromJson` factory constructor.
65
+ - [ ] 2. Implement the network request method returning a `Future<Model>`.
66
+ - [ ] 3. Apply conditional logic based on the operation type:
67
+ - **If fetching data (GET):** Append query parameters to the URI.
68
+ - **If mutating data (POST/PUT):** Set `'Content-Type': 'application/json; charset=UTF-8'` and attach the `jsonEncode` body.
69
+ - **If deleting data (DELETE):** Return an empty model instance on success (`200 OK`).
70
+ - [ ] 4. Validate the `statusCode` and throw an `Exception` on failure.
71
+ - [ ] 5. Integrate the `Future` into the UI using `FutureBuilder`.
72
+ - [ ] 6. Handle `snapshot.hasData`, `snapshot.hasError`, and default to a `CircularProgressIndicator`.
73
+ - [ ] 7. **Feedback Loop:** Run the app -> trigger the network request -> review console for unhandled exceptions -> fix parsing or permission errors.
74
+
75
+ ## Examples
76
+
77
+ ### High-Fidelity Implementation: Fetching and Parsing in the Background
78
+
79
+ ```dart
80
+ import 'dart:async';
81
+ import 'dart:convert';
82
+ import 'dart:io';
83
+ import 'package:flutter/foundation.dart';
84
+ import 'package:flutter/material.dart';
85
+ import 'package:http/http.dart' as http;
86
+
87
+ // 1. Top-level parsing function for Isolate
88
+ List<Photo> parsePhotos(String responseBody) {
89
+ final parsed = (jsonDecode(responseBody) as List<Object?>)
90
+ .cast<Map<String, Object?>>();
91
+ return parsed.map<Photo>(Photo.fromJson).toList();
92
+ }
93
+
94
+ // 2. Network execution with background parsing
95
+ Future<List<Photo>> fetchPhotos() async {
96
+ final response = await http.get(
97
+ Uri.parse('https://jsonplaceholder.typicode.com/photos'),
98
+ headers: {
99
+ HttpHeaders.authorizationHeader: 'Bearer your_token_here',
100
+ HttpHeaders.acceptHeader: 'application/json',
101
+ },
102
+ );
103
+
104
+ if (response.statusCode == 200) {
105
+ // Offload heavy parsing to a background isolate
106
+ return compute(parsePhotos, response.body);
107
+ } else {
108
+ throw Exception('Failed to load photos. Status: ${response.statusCode}');
109
+ }
110
+ }
111
+
112
+ // 3. Strongly typed model
113
+ class Photo {
114
+ final int id;
115
+ final String title;
116
+ final String thumbnailUrl;
117
+
118
+ const Photo({
119
+ required this.id,
120
+ required this.title,
121
+ required this.thumbnailUrl,
122
+ });
123
+
124
+ factory Photo.fromJson(Map<String, dynamic> json) {
125
+ return Photo(
126
+ id: json['id'] as int,
127
+ title: json['title'] as String,
128
+ thumbnailUrl: json['thumbnailUrl'] as String,
129
+ );
130
+ }
131
+ }
132
+
133
+ // 4. UI Integration
134
+ class PhotoGallery extends StatefulWidget {
135
+ const PhotoGallery({super.key});
136
+
137
+ @override
138
+ State<PhotoGallery> createState() => _PhotoGalleryState();
139
+ }
140
+
141
+ class _PhotoGalleryState extends State<PhotoGallery> {
142
+ late Future<List<Photo>> _futurePhotos;
143
+
144
+ @override
145
+ void initState() {
146
+ super.initState();
147
+ // Initialize Future once to prevent re-fetching on rebuilds
148
+ _futurePhotos = fetchPhotos();
149
+ }
150
+
151
+ @override
152
+ Widget build(BuildContext context) {
153
+ return FutureBuilder<List<Photo>>(
154
+ future: _futurePhotos,
155
+ builder: (context, snapshot) {
156
+ if (snapshot.hasData) {
157
+ final photos = snapshot.data!;
158
+ return ListView.builder(
159
+ itemCount: photos.length,
160
+ itemBuilder: (context, index) => ListTile(
161
+ leading: Image.network(photos[index].thumbnailUrl),
162
+ title: Text(photos[index].title),
163
+ ),
164
+ );
165
+ } else if (snapshot.hasError) {
166
+ return Center(child: Text('Error: ${snapshot.error}'));
167
+ }
168
+
169
+ // Default loading state
170
+ return const Center(child: CircularProgressIndicator());
171
+ },
172
+ );
173
+ }
174
+ }
175
+ ```
176
+
177
+ ## Flutter Ultra Integration
178
+
179
+ Monitor and debug HTTP calls in the running app:
180
+
181
+ - `mcp__plugin_flutter_flutter-ultra-runtime__start_http_capture` — Start capturing HTTP traffic
182
+ - `mcp__plugin_flutter_flutter-ultra-runtime__get_http_events` — View captured HTTP requests and responses
183
+ - `mcp__plugin_flutter_flutter-ultra-runtime__stop_http_capture` — Stop HTTP capture
184
+ - `mcp__plugin_flutter_flutter-ultra-runtime__get_runtime_errors` — Check for unhandled HTTP exceptions
185
+
186
+ ---
187
+
188
+ > **Attribution:** This skill is vendored from [flutter/skills](https://github.com/flutter/skills) (BSD-3-Clause).
189
+ > Synced by `scripts/sync-upstream-skills.mjs`. Do not edit manually — changes will be overwritten on next sync.
@@ -0,0 +1,169 @@
1
+ ---
2
+ name: use-pattern-matching
3
+ description: Use switch expressions and pattern matching where appropriate
4
+ last_modified: Fri, 24 Apr 2026 15:08:55 GMT
5
+ ---
6
+
7
+ # Implementing Dart Patterns
8
+
9
+ ## Contents
10
+
11
+ - [Pattern Selection Strategy](#pattern-selection-strategy)
12
+ - [Switch Statements vs. Expressions](#switch-statements-vs-expressions)
13
+ - [Core Pattern Implementations](#core-pattern-implementations)
14
+ - [Workflows](#workflows)
15
+ - [Examples](#examples)
16
+
17
+ ## Pattern Selection Strategy
18
+
19
+ Apply specific pattern types based on the data structure and desired outcome. Follow these conditional guidelines:
20
+
21
+ - **If validating and extracting from deserialized data (e.g., JSON):** Use Map and List patterns to simultaneously check structure and destructure key-value pairs.
22
+ - **If handling multiple return values:** Use Record patterns to destructure fields directly into local variables.
23
+ - **If executing type-specific behavior (Algebraic Data Types):** Use Object patterns combined with `sealed` classes to ensure exhaustiveness.
24
+ - **If matching numeric ranges or conditions:** Use Relational (`>=`, `<=`) and Logical-and (`&&`) patterns.
25
+ - **If multiple cases share logic:** Use Logical-or (`||`) patterns to share a single case body or guard clause.
26
+ - **If ignoring specific values:** Use the Wildcard pattern (`_`) or a non-matching Rest element (`...`) in collections.
27
+
28
+ ## Switch Statements vs. Expressions
29
+
30
+ Select the appropriate switch construct based on the execution context:
31
+
32
+ - **If producing a value:** Use a **switch expression**.
33
+ - Syntax: `switch (value) { pattern => expression, }`
34
+ - Rule: Each case must be a single expression. No implicit fallthrough. Must be exhaustive.
35
+ - **If executing statements or side effects:** Use a **switch statement**.
36
+ - Syntax: `switch (value) { case pattern: statements; }`
37
+ - Rule: Empty cases fall through to the next case. Non-empty cases implicitly break (no `break` keyword required).
38
+
39
+ ## Core Pattern Implementations
40
+
41
+ Implement patterns using the following syntax and rules:
42
+
43
+ - **Logical-or (`||`):** `pattern1 || pattern2`. Both branches must define the exact same set of variables.
44
+ - **Logical-and (`&&`):** `pattern1 && pattern2`. Branches must _not_ define overlapping variables.
45
+ - **Relational:** `==`, `!=`, `<`, `>`, `<=`, `>=` followed by a constant expression.
46
+ - **Cast (`as`):** `pattern as Type`. Throws if the value does not match the type. Use to forcibly assert types during destructuring.
47
+ - **Null-check (`?`):** `pattern?`. Fails the match if the value is null. Binds the variable to the non-nullable base type.
48
+ - **Null-assert (`!`):** `pattern!`. Throws if the value is null.
49
+ - **Variable:** `var name` or `Type name`. Binds the matched value to a new local variable.
50
+ - **Wildcard (`_`):** Matches any value and discards it.
51
+ - **List:** `[pattern1, pattern2]`. Matches lists of exact length unless a Rest element (`...` or `...var rest`) is used.
52
+ - **Map:** `{"key": pattern}`. Matches maps containing the specified keys. Ignores unmatched keys.
53
+ - **Record:** `(pattern1, named: pattern2)`. Matches records of the exact shape. Use `:var name` to infer the getter name.
54
+ - **Object:** `ClassName(field: pattern)`. Matches instances of `ClassName`. Use `:var field` to infer the getter name.
55
+
56
+ ## Workflows
57
+
58
+ ### Task Progress: Implementing Pattern Matching
59
+
60
+ Copy this checklist to track progress when implementing complex pattern matching logic:
61
+
62
+ - [ ] Identify the data structure being evaluated (JSON, Record, Class, Enum).
63
+ - [ ] Select the appropriate switch construct (Expression for values, Statement for side-effects).
64
+ - [ ] Define the required patterns (Object, Map, List, Record).
65
+ - [ ] Extract required data using Variable patterns (`var x`, `:var y`).
66
+ - [ ] Apply Guard clauses (`when condition`) for logic that cannot be expressed via patterns.
67
+ - [ ] Handle unmatched cases using a Wildcard (`_`) or `default` clause (if not using a sealed class).
68
+ - [ ] Run exhaustiveness validator.
69
+
70
+ ### Feedback Loop: Exhaustiveness Checking
71
+
72
+ When switching over `sealed` classes or enums, you must ensure all subtypes are handled.
73
+
74
+ 1. **Run validator:** Execute `dart analyze`.
75
+ 2. **Review errors:** Look for "The type 'X' is not exhaustively matched by the switch cases" errors.
76
+ 3. **Fix:** Add the missing Object patterns for the unhandled subtypes, or add a Wildcard (`_`) case if a default fallback is acceptable.
77
+
78
+ ## Examples
79
+
80
+ ### JSON Validation and Destructuring
81
+
82
+ Use Map and List patterns to validate structure and extract data in a single step.
83
+
84
+ **Input:**
85
+
86
+ ```dart
87
+ var data = {
88
+ 'user': ['Lily', 13],
89
+ };
90
+ ```
91
+
92
+ **Implementation:**
93
+
94
+ ```dart
95
+ if (data case {'user': [String name, int age]}) {
96
+ print('User $name is $age years old.');
97
+ } else {
98
+ print('Invalid JSON structure.');
99
+ }
100
+ ```
101
+
102
+ ### Algebraic Data Types (Sealed Classes)
103
+
104
+ Use Object patterns with switch expressions to handle family types exhaustively.
105
+
106
+ **Implementation:**
107
+
108
+ ```dart
109
+ sealed class Shape {}
110
+
111
+ class Square implements Shape {
112
+ final double length;
113
+ Square(this.length);
114
+ }
115
+
116
+ class Circle implements Shape {
117
+ final double radius;
118
+ Circle(this.radius);
119
+ }
120
+
121
+ // Switch expression guarantees exhaustiveness due to `sealed` modifier.
122
+ double calculateArea(Shape shape) => switch (shape) {
123
+ Square(length: var l) => l * l,
124
+ Circle(:var radius) => math.pi * radius * radius,
125
+ };
126
+ ```
127
+
128
+ ### Variable Swapping and Destructuring
129
+
130
+ Use variable assignment patterns to swap values or extract record fields without temporary variables.
131
+
132
+ **Implementation:**
133
+
134
+ ```dart
135
+ var (a, b) = ('left', 'right');
136
+ (b, a) = (a, b); // Swap values
137
+
138
+ // Destructuring a function return
139
+ var (name, age) = getUserInfo();
140
+ ```
141
+
142
+ ### Guard Clauses and Logical-or
143
+
144
+ Use `when` to evaluate arbitrary conditions after a pattern matches.
145
+
146
+ **Implementation:**
147
+
148
+ ```dart
149
+ switch (shape) {
150
+ case Square(size: var s) || Circle(size: var s) when s > 0:
151
+ print('Valid symmetric shape with size $s');
152
+ case Square() || Circle():
153
+ print('Invalid or empty shape');
154
+ default:
155
+ print('Unknown shape');
156
+ }
157
+ ```
158
+
159
+ ## Flutter Ultra Integration
160
+
161
+ Validate pattern matching usage with analysis:
162
+
163
+ - `mcp__plugin_flutter_flutter-ultra-build__analyze` — Check for exhaustiveness and type errors
164
+ - `mcp__plugin_flutter_flutter-ultra-build__fix` — Apply automated pattern matching migrations
165
+
166
+ ---
167
+
168
+ > **Attribution:** This skill is vendored from [dart-lang/skills](https://github.com/dart-lang/skills) (BSD-3-Clause).
169
+ > Synced by `scripts/sync-upstream-skills.mjs`. Do not edit manually — changes will be overwritten on next sync.