用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/xuelongqy/flutter_easy_refresh --skill flutter-state-management命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
基于 SOC 职业分类
正在显示 SKILL.md
| name | flutter-state-management |
| description | Manage state in your Flutter application |
| metadata | {"model":"models/gemini-3.1-pro-preview","last_modified":"Tue, 03 Mar 2026 20:44:13 GMT"} |
Implements robust state management and architectural patterns in Flutter applications using Unidirectional Data Flow (UDF) and the Model-View-ViewModel (MVVM) design pattern. Evaluates state complexity to differentiate between ephemeral (local) state and app (shared) state, applying the appropriate mechanisms (setState, ChangeNotifier, or the provider package). Ensures that the UI remains a pure function of immutable state and that the data layer acts as the Single Source of Truth (SSOT).
Evaluate the data requirements of the feature to determine the appropriate state management approach. Use the following decision tree:
PageView, animation progress, local form input)
StatefulWidget + setState).ChangeNotifier + provider).STOP AND ASK THE USER: If the scope of the state (ephemeral vs. app-wide) is ambiguous based on the provided requirements, pause and ask the user to clarify the intended scope and lifecycle of the data.
For local UI state, use a StatefulWidget. Ensure that setState() is called immediately when the internal state is modified to mark the widget as dirty and schedule a rebuild.
class LocalStateWidget extends StatefulWidget {
const LocalStateWidget({super.key});
@override
State<LocalStateWidget> createState() => _LocalStateWidgetState();
}
class _LocalStateWidgetState extends State<LocalStateWidget> {
bool _isToggled = false;
void _handleToggle() {
// Validate-and-Fix: Ensure setState wraps the mutation.
setState(() {
_isToggled = !_isToggled;
});
}
@override
Widget build(BuildContext context) {
return Switch(
value: _isToggled,
onChanged: (value) => _handleToggle(),
);
}
}
For shared state, implement the MVVM pattern enforcing Unidirectional Data Flow (UDF).
A. Create the Model (Data Layer / SSOT) Handle low-level tasks (HTTP, caching) in a Repository class.
class UserRepository {
Future<User> fetchUser(String id) async {
// Implementation for fetching user data
}
}
B. Create the ViewModel (Logic Layer)
Extend ChangeNotifier. The ViewModel converts app data into UI state and exposes commands (methods) for the View to invoke.
class UserViewModel extends ChangeNotifier {
UserViewModel({required this.userRepository});
final UserRepository userRepository;
User? _user;
User? get user => _user;
bool _isLoading = false;
bool get isLoading => _isLoading;
String? _errorMessage;
String? get errorMessage => _errorMessage;
// Command invoked by the UI
Future<void> loadUser(String id) async {
_isLoading = true;
_errorMessage = null;
notifyListeners(); // Trigger loading UI
try {
_user = await userRepository.fetchUser(id);
} catch (e) {
_errorMessage = e.toString();
} finally {
_isLoading = false;
notifyListeners(); // Trigger success/error UI
}
}
}
Use the provider package to inject the ViewModel into the widget tree above the widgets that require access to it.
void main() {
runApp(
MultiProvider(
providers: [
Provider(create: (_) => UserRepository()),
ChangeNotifierProvider(
create: (context) => UserViewModel(
userRepository: context.read<UserRepository>(),
),
),
],
child: const MyApp(),
),
);
}
Build the UI as a function of the ViewModel's state. Use Consumer to rebuild only the specific parts of the UI that depend on the state.
class UserProfileView extends StatelessWidget {
const UserProfileView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Consumer<UserViewModel>(
builder: (context, viewModel, child) {
if (viewModel.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (viewModel.errorMessage != null) {
return Center(child: Text('Error: ${viewModel.errorMessage}'));
}
if (viewModel.user != null) {
return Center(child: Text('Hello, ${viewModel.user!.name}'));
}
return const Center(child: Text('No user loaded.'));
},
),
floatingActionButton: FloatingActionButton(
// Use listen: false when invoking commands outside the build method
onPressed: () => context.read<UserViewModel>().loadUser('123'),
child: const Icon(Icons.refresh),
),
);
}
}
Validate-and-Fix: Verify that Consumer is placed as deep in the widget tree as possible to prevent unnecessary rebuilds of large widget subtrees.
StatelessWidget and StatefulWidget classes must only contain UI, layout, and routing logic. All data transformation and business logic MUST reside in the ViewModel.Provider.of<T>(context) with listen: true at the root of a large build method if only a small child needs the data. Use Consumer<T> or Selector<T, R> to scope rebuilds.onPressed), you MUST use context.read<T>() or Provider.of<T>(context, listen: false).notifyListeners().