moai-lang-flutter
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseQuick Reference (30 seconds)
快速参考(30秒)
Flutter/Dart Development Expert - Dart 3.5+, Flutter 3.24+ with modern patterns.
Auto-Triggers: Flutter projects ( files, ), cross-platform apps, widget development
.dartpubspec.yamlCore Capabilities:
- Dart 3.5: Patterns, records, sealed classes, extension types
- Flutter 3.24: Widget tree, Material 3, adaptive layouts
- Riverpod: State management with code generation
- go_router: Declarative navigation and deep linking
- Platform Channels: Native iOS/Android integration
- Testing: flutter_test, widget_test, integration_test
Flutter/Dart开发专家 - Dart 3.5+、Flutter 3.24+ 及现代开发模式。
自动触发场景:Flutter项目(文件、)、跨平台应用、组件开发
.dartpubspec.yaml核心能力:
- Dart 3.5:模式匹配、记录类型、密封类、扩展类型
- Flutter 3.24:组件树、Material 3、自适应布局
- Riverpod:带代码生成的状态管理
- go_router:声明式导航与深度链接
- 平台通道:原生iOS/Android集成
- 测试:flutter_test、widget_test、integration_test
Implementation Guide (5 minutes)
实现指南(5分钟)
Dart 3.5 Language Features
Dart 3.5语言特性
Pattern Matching with Sealed Classes: Define a sealed class Result with generic type parameter T. Create subclasses Success containing data field and Failure containing error string. Use switch expressions with pattern matching on the sealed type. Patterns use colon syntax to extract named fields. Add guard clauses with when keyword for conditional matching based on field values.
Records and Destructuring: Define type aliases for records using parentheses with named fields. Create functions returning multiple values as record tuples with positional elements. Use destructuring syntax with parentheses on the left side of assignment. In for loops, destructure named record fields directly using colon syntax.
Extension Types: Define extension types with the type keyword, wrapping a base type in parentheses. Add factory constructors for validation logic. Define getters for computed properties on the underlying value.
使用密封类进行模式匹配:定义一个带泛型参数T的密封类Result。创建包含data字段的Success子类和包含error字符串的Failure子类。在密封类型上使用switch表达式进行模式匹配。使用冒号语法的模式来提取命名字段。使用when关键字添加守卫子句,基于字段值进行条件匹配。
记录类型与解构:使用带命名字段的括号定义记录类型的别名。创建返回多个值的函数,将其作为带位置元素的记录元组返回。在赋值语句的左侧使用括号解构语法。在for循环中,直接使用冒号语法解构记录的命名字段。
扩展类型:使用type关键字定义扩展类型,在括号中包裹基础类型。添加工厂构造函数用于验证逻辑。为底层值定义计算属性的getter方法。
Riverpod State Management
Riverpod状态管理
Provider Definitions: Import riverpod_annotation and add part directive for generated file. Use @riverpod annotation on functions to create simple providers. Return repository instances reading other providers with ref.read. Create async providers by returning Future types. For stateful providers, create classes extending the generated underscore class, override build method for initial state, and add methods that modify state using AsyncValue.guard.
Widget Integration: Create ConsumerWidget subclasses. In build method, receive WidgetRef as second parameter. Use ref.watch to observe provider values. Handle AsyncValue with when method providing data, loading, and error callbacks. Use ref.invalidate to refresh data. Use ref.listen in StatefulWidget for side effects like showing snackbars.
StatefulWidget with Riverpod: Extend ConsumerStatefulWidget and ConsumerState. Initialize TextEditingController in initState and dispose in dispose. Use ref.listen in build for side effects. Check isLoading state to disable buttons during async operations. Access notifier methods with ref.read and the notifier getter.
Provider定义:导入riverpod_annotation并添加part指令用于生成文件。在函数上使用@riverpod注解创建简单的Provider。返回通过ref.read读取其他Provider的仓库实例。通过返回Future类型创建异步Provider。对于有状态的Provider,创建继承自生成的下划线类的类,重写build方法设置初始状态,并添加使用AsyncValue.guard修改状态的方法。
组件集成:创建ConsumerWidget子类。在build方法中,接收WidgetRef作为第二个参数。使用ref.watch观察Provider的值。使用when方法处理AsyncValue,提供data、loading和error回调。使用ref.invalidate刷新数据。在StatefulWidget中使用ref.listen处理副作用,比如显示snackbar。
结合Riverpod的StatefulWidget:继承ConsumerStatefulWidget和ConsumerState。在initState中初始化TextEditingController,在dispose中销毁。在build中使用ref.listen处理副作用。检查isLoading状态以在异步操作期间禁用按钮。使用ref.read和notifier getter访问通知器方法。
go_router Navigation
go_router导航
Router Configuration: Create GoRouter instance with initialLocation. Define routes array with GoRoute objects containing path, name, and builder. Nest child routes in routes array. Use ShellRoute for persistent navigation shells. Create pageBuilder using NoTransitionPage for tab navigation. Implement redirect callback checking authentication state and returning redirect path or null to allow navigation. Define errorBuilder for error handling.
Navigation methods: Use context.go for declarative navigation with path. Use context.canPop to check before context.pop.
路由配置:创建带initialLocation的GoRouter实例。定义包含path、name和builder的GoRoute对象数组。在routes数组中嵌套子路由。使用ShellRoute实现持久化导航外壳。使用NoTransitionPage创建pageBuilder用于标签页导航。实现redirect回调检查认证状态,返回重定向路径或null以允许导航。定义errorBuilder处理错误。
导航方法:使用context.go进行基于路径的声明式导航。在调用context.pop前使用context.canPop检查是否可返回。
Platform Channels
平台通道
Dart Implementation: Define class with MethodChannel and EventChannel constants using channel name strings. Create async methods that invoke methods on the channel with invokeMethod, catching PlatformException. For streaming data, call receiveBroadcastStream on EventChannel and map events to typed objects. Set up method call handler with setMethodCallHandler to receive calls from native code.
Dart实现:定义包含MethodChannel和EventChannel常量的类,使用通道名字符串。创建异步方法,通过invokeMethod调用通道上的方法,并捕获PlatformException。对于流式数据,调用EventChannel的receiveBroadcastStream并将事件映射为类型化对象。使用setMethodCallHandler设置方法调用处理器,接收来自原生代码的调用。
Widget Patterns
组件模式
Adaptive Layouts: Create StatelessWidget with required parameters for child, destinations, selectedIndex, and onDestinationSelected callback. In build, get width using MediaQuery.sizeOf. Use conditional returns based on width breakpoints. Under 600 pixels, return Scaffold with NavigationBar in bottomNavigationBar. Under 840 pixels, return Scaffold with Row containing NavigationRail and expanded child. Above 840 pixels, return Scaffold with Row containing NavigationDrawer and expanded child.
自适应布局:创建带child、destinations、selectedIndex和onDestinationSelected回调必填参数的StatelessWidget。在build中,使用MediaQuery.sizeOf获取宽度。基于宽度断点进行条件返回。宽度小于600像素时,返回在bottomNavigationBar中包含NavigationBar的Scaffold。宽度小于840像素时,返回包含NavigationRail和扩展子组件的Row的Scaffold。宽度大于840像素时,返回包含NavigationDrawer和扩展子组件的Row的Scaffold。
Testing
测试
Widget Test Example: In test main function, create ProviderContainer with overrides for mock providers. Use tester.pumpWidget with UncontrolledProviderScope wrapping MaterialApp with the widget under test. Assert initial loading state with find.byType. Call tester.pumpAndSettle to wait for async operations. Assert final state with find.text.
For comprehensive testing patterns, see examples.md.
组件测试示例:在测试main函数中,创建带模拟Provider覆盖的ProviderContainer。使用tester.pumpWidget,用UncontrolledProviderScope包裹包含待测试组件的MaterialApp。使用find.byType断言初始加载状态。调用tester.pumpAndSettle等待异步操作完成。使用find.text断言最终状态。
如需完整测试模式,请查看examples.md。
Advanced Patterns
高级模式
For comprehensive coverage including:
- Clean Architecture with Riverpod
- Isolates for compute-heavy operations
- Custom render objects and painting
- FFI and platform-specific plugins
- Performance optimization and profiling
See: reference.md and examples.md
如需涵盖以下内容的完整指南:
- 结合Riverpod的整洁架构
- 用于计算密集型操作的Isolate
- 自定义渲染对象与绘制
- FFI与平台特定插件
- 性能优化与分析
请查看:reference.md和examples.md
Context7 Library Mappings
Context7库映射
Flutter/Dart Core:
- - Flutter framework
/flutter/flutter - - Dart SDK
/dart-lang/sdk
State Management:
- - Riverpod state management
/rrousselGit/riverpod - - BLoC pattern
/felangel/bloc
Navigation and Storage:
- - go_router and official packages
/flutter/packages - - HTTP client
/cfug/dio - - NoSQL database
/isar/isar
Flutter/Dart核心:
- - Flutter框架
/flutter/flutter - - Dart SDK
/dart-lang/sdk
状态管理:
- - Riverpod状态管理
/rrousselGit/riverpod - - BLoC模式
/felangel/bloc
导航与存储:
- - go_router及官方包
/flutter/packages - - HTTP客户端
/cfug/dio - - NoSQL数据库
/isar/isar
Works Well With
适配工具
- - iOS native integration for platform channels
moai-lang-swift - - Android native integration for platform channels
moai-lang-kotlin - - API integration and backend communication
moai-domain-backend - - Mobile security best practices
moai-quality-security - - Flutter debugging and DevTools
moai-essentials-debug
- - 用于平台通道的iOS原生集成
moai-lang-swift - - 用于平台通道的Android原生集成
moai-lang-kotlin - - API集成与后端通信
moai-domain-backend - - 移动安全最佳实践
moai-quality-security - - Flutter调试与DevTools
moai-essentials-debug