ERP/.shared/ui-ux-pro-max/data/stacks/flutter.csv
2026-01-03 19:18:40 +08:00

10 KiB

1NoCategoryGuidelineDescriptionDoDon'tCode GoodCode BadSeverityDocs URL
21WidgetsUse StatelessWidget when possibleImmutable widgets are simplerStatelessWidget for static UIStatefulWidget for everythingclass MyWidget extends StatelessWidgetclass MyWidget extends StatefulWidget (static)Mediumhttps://api.flutter.dev/flutter/widgets/StatelessWidget-class.html
32WidgetsKeep widgets smallSingle responsibility principleExtract widgets into smaller piecesLarge build methodsColumn(children: [Header() Content()])500+ line build methodMedium
43WidgetsUse const constructorsCompile-time constants for performanceconst MyWidget() when possibleNon-const for static widgetsconst Text('Hello')Text('Hello') for literalsHighhttps://dart.dev/guides/language/language-tour#constant-constructors
54WidgetsPrefer composition over inheritanceCombine widgets using childrenCompose widgetsExtend widget classesContainer(child: MyContent())class MyContainer extends ContainerMedium
65StateUse setState correctlyMinimal state in StatefulWidgetsetState for UI state changessetState for business logicsetState(() { _counter++; })Complex logic in setStateMediumhttps://api.flutter.dev/flutter/widgets/State/setState.html
76StateAvoid setState in buildNever call setState during buildsetState in callbacks onlysetState in build methodonPressed: () => setState(() {})build() { setState(); }High
87StateUse state management for complex appsProvider Riverpod BLoCState management for shared statesetState for global stateProvider.of<MyState>(context)Global setState callsMedium
98StatePrefer Riverpod or ProviderRecommended state solutionsRiverpod for new projectsInheritedWidget manuallyref.watch(myProvider)Custom InheritedWidgetMediumhttps://riverpod.dev/
109StateDispose resourcesClean up controllers and subscriptionsdispose() for cleanupMemory leaks from subscriptions@override void dispose() { controller.dispose(); }No dispose implementationHigh
1110LayoutUse Column and RowBasic layout widgetsColumn Row for linear layoutsStack for simple layoutsColumn(children: [Text(), Button()])Stack for vertical listMediumhttps://api.flutter.dev/flutter/widgets/Column-class.html
1211LayoutUse Expanded and FlexibleControl flex behaviorExpanded to fill spaceFixed sizes in flex containersExpanded(child: Container())Container(width: 200) in RowMedium
1312LayoutUse SizedBox for spacingConsistent spacingSizedBox for gapsContainer for spacing onlySizedBox(height: 16)Container(height: 16)Low
1413LayoutUse LayoutBuilder for responsiveRespond to constraintsLayoutBuilder for adaptive layoutsFixed sizes for responsiveLayoutBuilder(builder: (context constraints) {})Container(width: 375)Mediumhttps://api.flutter.dev/flutter/widgets/LayoutBuilder-class.html
1514LayoutAvoid deep nestingKeep widget tree shallowExtract deeply nested widgets10+ levels of nestingExtract widget to method or classColumn(Row(Column(Row(...))))Medium
1615ListsUse ListView.builderLazy list buildingListView.builder for long listsListView with children for large listsListView.builder(itemCount: 100, itemBuilder: ...)ListView(children: items.map(...).toList())Highhttps://api.flutter.dev/flutter/widgets/ListView-class.html
1716ListsProvide itemExtent when knownSkip measurementitemExtent for fixed height itemsNo itemExtent for uniform listsListView.builder(itemExtent: 50)ListView.builder without itemExtentMedium
1817ListsUse keys for stateful itemsPreserve widget stateKey for stateful list itemsNo key for dynamic listsListTile(key: ValueKey(item.id))ListTile without keyHigh
1918ListsUse SliverList for custom scrollCustom scroll effectsCustomScrollView with SliversNested ListViewsCustomScrollView(slivers: [SliverList()])ListView inside ListViewMediumhttps://api.flutter.dev/flutter/widgets/SliverList-class.html
2019NavigationUse Navigator 2.0 or GoRouterDeclarative routinggo_router for navigationNavigator.push for complex appsGoRouter(routes: [...])Navigator.push everywhereMediumhttps://pub.dev/packages/go_router
2120NavigationUse named routesOrganized navigationNamed routes for clarityAnonymous routesNavigator.pushNamed(context '/home')Navigator.push(context MaterialPageRoute())Low
2221NavigationHandle back button (PopScope)Android back behavior and predictive back (Android 14+)Use PopScope widget (WillPopScope is deprecated)Use WillPopScopePopScope(canPop: false, onPopInvoked: (didPop) => ...)WillPopScope(onWillPop: ...)Highhttps://api.flutter.dev/flutter/widgets/PopScope-class.html
2322NavigationPass typed argumentsType-safe route argumentsTyped route argumentsDynamic argumentsMyRoute(id: '123')arguments: {'id': '123'}Medium
2423AsyncUse FutureBuilderAsync UI buildingFutureBuilder for async datasetState for asyncFutureBuilder(future: fetchData())fetchData().then((d) => setState())Mediumhttps://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
2524AsyncUse StreamBuilderStream UI buildingStreamBuilder for streamsManual stream subscriptionStreamBuilder(stream: myStream)stream.listen in initStateMediumhttps://api.flutter.dev/flutter/widgets/StreamBuilder-class.html
2625AsyncHandle loading and error statesComplete async UI statesConnectionState checksOnly success stateif (snapshot.connectionState == ConnectionState.waiting)No loading indicatorHigh
2726AsyncCancel subscriptionsClean up stream subscriptionsCancel in disposeMemory leakssubscription.cancel() in disposeNo subscription cleanupHigh
2827ThemingUse ThemeDataConsistent themingThemeData for app themeHardcoded colorsTheme.of(context).primaryColorColor(0xFF123456) everywhereMediumhttps://api.flutter.dev/flutter/material/ThemeData-class.html
2928ThemingUse ColorSchemeMaterial 3 color systemColorScheme for colorsIndividual color propertiescolorScheme: ColorScheme.fromSeed()primaryColor: Colors.blueMedium
3029ThemingAccess theme via contextDynamic theme accessTheme.of(context)Static theme referenceTheme.of(context).textTheme.bodyLargeTextStyle(fontSize: 16)Medium
3130ThemingSupport dark modeRespect system themedarkTheme in MaterialAppLight theme onlyMaterialApp(theme: light, darkTheme: dark)MaterialApp(theme: light)Medium
3231AnimationUse implicit animationsSimple animationsAnimatedContainer AnimatedOpacityExplicit for simple transitionsAnimatedContainer(duration: Duration())AnimationController for fadeLowhttps://api.flutter.dev/flutter/widgets/AnimatedContainer-class.html
3332AnimationUse AnimationController for complexFine-grained controlAnimationController with TickerImplicit for complex sequencesAnimationController(vsync: this)AnimatedContainer for staggeredMedium
3433AnimationDispose AnimationControllersClean up animation resourcesdispose() for controllersMemory leakscontroller.dispose() in disposeNo controller disposalHigh
3534AnimationUse Hero for transitionsShared element transitionsHero for navigation animationsManual shared elementHero(tag: 'image' child: Image())Custom shared element animationLowhttps://api.flutter.dev/flutter/widgets/Hero-class.html
3635FormsUse Form widgetForm validationForm with GlobalKeyIndividual validationForm(key: _formKey child: ...)TextField without FormMediumhttps://api.flutter.dev/flutter/widgets/Form-class.html
3736FormsUse TextEditingControllerControl text inputController for text fieldsonChanged for all textfinal controller = TextEditingController()onChanged: (v) => setState()Medium
3837FormsValidate on submitForm validation flow_formKey.currentState!.validate()Skip validationif (_formKey.currentState!.validate())Submit without validationHigh
3938FormsDispose controllersClean up text controllersdispose() for controllersMemory leakscontroller.dispose() in disposeNo controller disposalHigh
4039PerformanceUse const widgetsReduce rebuildsconst for static widgetsNo const for literalsconst Icon(Icons.add)Icon(Icons.add)High
4140PerformanceAvoid rebuilding entire treeMinimal rebuild scopeIsolate changing widgetssetState on parentConsumer only around changing widgetsetState on root widgetHigh
4241PerformanceUse RepaintBoundaryIsolate repaintsRepaintBoundary for animationsFull screen repaintsRepaintBoundary(child: AnimatedWidget())Animation without boundaryMediumhttps://api.flutter.dev/flutter/widgets/RepaintBoundary-class.html
4342PerformanceProfile with DevToolsMeasure before optimizingFlutter DevTools profilingGuess at performanceDevTools performance tabOptimize without measuringMediumhttps://docs.flutter.dev/tools/devtools
4443AccessibilityUse Semantics widgetScreen reader supportSemantics for accessibilityMissing accessibility infoSemantics(label: 'Submit button')GestureDetector without semanticsHighhttps://api.flutter.dev/flutter/widgets/Semantics-class.html
4544AccessibilitySupport large fontsMediaQuery text scalingMediaQuery.textScaleFactorFixed font sizesstyle: Theme.of(context).textThemeTextStyle(fontSize: 14)High
4645AccessibilityTest with screen readersTalkBack and VoiceOverTest accessibility regularlySkip accessibility testingRegular TalkBack testingNo screen reader testingHigh
4746TestingUse widget testsTest widget behaviorWidgetTester for UI testsUnit tests onlytestWidgets('...' (tester) async {})Only test() for UIMediumhttps://docs.flutter.dev/testing
4847TestingUse integration testsFull app testingintegration_test packageManual testing onlyIntegrationTestWidgetsFlutterBindingManual E2E testingMedium
4948TestingMock dependenciesIsolate testsMockito or mocktailReal dependencies in testswhen(mock.method()).thenReturn()Real API calls in testsMedium
5049PlatformUse Platform checksPlatform-specific codePlatform.isIOS Platform.isAndroidSame code for all platformsif (Platform.isIOS) {}Hardcoded iOS behaviorMedium
5150PlatformUse kIsWeb for webWeb platform detectionkIsWeb for web checksPlatform for webif (kIsWeb) {}Platform.isWeb (doesn't exist)Medium
5251PackagesUse pub.dev packagesCommunity packagesPopular maintained packagesCustom implementationscached_network_imageCustom image cacheMediumhttps://pub.dev/
5352PackagesCheck package qualityQuality before addingPub points and popularityAny package without review100+ pub pointsUnmaintained packagesMedium