Internalization
- add
flutter_localizationspackage as dependency - add
intlpackage dependency - add
generate: trueunderpubspec.yaml - flutter - add
l10n.yaml- with
arb-dir,template-arb-file,output-localization-file
- with
- provides localized strings and values for library
GlobalMaterialLocalizations.delegateGlobalWidgetsLocalizations.delegate
Localelanguage code entries in IANA Language Subtag RegistryLocalizations.localOf()get app current locale
Networking
Test project:
Notes:
httppakcage, composable and Future-based library for making HTTP requestFutureis core Dart class for working with async operations. Future object represents potential value/error thatwill be available at some time in the futurehttp.Responsecontains data received from a successful http callFutureBuilderwidget to display data on screensnapshot.hasDataonly returnstruewhen snapshot contains a non-null data value
JSON and Serialization
Manual serialization
- use built-in JSON decoder in
dart:convert- serialize JSON inline
jsonDecode()returnMap<String, dynamic>- don’t know the types of values until runtime, lose statically typed language features: type safety, autocompletion, compile-time exceptions
- serialize JSON inside model classes
.fromJson()for constructing from map structuretoJson()convert to a map- type safety
- serialize JSON inline
Automated serialization using code generation
- have external library generate the encoding boilerplate, run file watcher that generates code from model classes, ex:
json_serializableandbuilt_valuejson_serializableallow to make regular classes serializing by using annotationsbuilt-valueprovides higher-level way of defining immutable value classes taht can also be serialized to JSON
- use it for medium or larger project
Effect
Test project:
Notes:
ClipRRect, widget clips using rounded rectanglecontext.findRenderObject() as RenderBoxreturn aRenderBoxto tell where the item areAlignment.inscribe()return rect of the given size, aligned within given rect as specifiedImagecan apply filters withcolorandcolorBlendModeLayoutBuilder: parent constrains the child’s size and doesn’t depend on the child’s intrinsic size.SizedBox.expand()create box become as large as its parent allowsIgnorePointerwidget is invisible when hit, disable interactionClipOval: widget clip with ovalScrollableListViewwidget always position first element at beginning of available space.PageViewwidget layout children from the center of the available space, and provides snapping physics.PageControllerhasviewportFractionused to display multiple item on screen at the same time- can
addListenerto controller, monitor changes - use
hasClientsandposition.hasContentDimensionsto check if there is PageView and PageController is attached animateToPagemove that item into center
- can
Flow, can control transform of a child widget immediately before widget paint, control where child is paintedFlowDelegatecontrol how its children are sized and where children are painted
CustomPaint, control what a child paintsRenderBox, control layout, painting, hit testing- for customize the position of child widgets within a scrollable area, use
ScrollablewithviewportBuilder, placeFlowwidget inside theviewportBuilder. TheFlowhas adelegate propertythat allows position child widget wherever we want, based on currentviewportOffset
ValueNotifiernotify when value changedValueListenableBuildercould use to listen this notifier
BoxFithow to fit another box, ex: contain, coverAlwaysStoppedAnimationanimation always stop at one timeChangeNotifierA class that can be extended or mixed in that provides a change notification API using VoidCallback for notifications.notifyLiseners()notify changes
Navigatorwidget to handle top-level navigation flowMaterialPageRoute<dynamic>construct MaterialPageRoute whose contents are defined by builderNavigatorState, the state for Navigator widget
GlobalKeyis key that is unique across the entire app- provide access to
State
- provide access to
PreferredSizeWidget, an interface for widget that ca nreturn size this widget prefer- for
AppBarandTabBar, widget needs to expose a preferred or default size
- for
WillPopScopecalback when user attempts to dismiss the enclosing ModalRouteAlertDialogto show alert dialogBoxDecoration, decorative way to draw a box, add borderRadius, color decorationElevatedButton, material design, buttons to add dimension to otherwise mosftly flat layoutMaterialStateProperty, interface for class resolve to value of T based on widget interactive state(MaterialState)StatefulWidgetcontains propertymounted, check if this state object is currently in a tree
Design
Test Project:
Notes:
Drawer: better use it from material library, which adheres to Material Design Spec- need a
AppBarto show it - use
Navigator.pop(context)to close drawer. When user open a drawer(menu), Flutter add drawer to navigation stack.
- need a
Scaffoldfrom material library, ensure widget won’t overlapSnackBar, can add action byaction: SnackBarActionScaffoldMessenger.ofcould use to show SnackBarOrientationBuilder: build different layout on landscape or portrait- use
MediaQuery.of(context).orientationcould get orientation of the screen - Flutter supports
.ttfand.otffont formats - set font as default: directly set app’s
theme(use fontFamily) - set font for specific widget: use
TextStyle(fontFamily) - app wide themes: define app’s
textTheme - create unique theme using
ThemeData Theme.copyWith()extend parent themeTabControllerbuild a tabbar controllerTabBar(tabs:[])create each tabBarItembody: TabBarView(children:)create each tabBar content view
Animation
Test project:
Notes:
PageRouteBuilderprovideAnimationobject- Animation can be used with
TweenandCurveobject to customize the transition animation childparam in transitionBuilder is widget returned from pageBuilder.pageBuilderonly called the first time the route is built. Framework can avoid extra work becausechildstays the same throughout the transition.
- Animation can be used with
FractionalTranslation, apply translation transformation before painting its childAnimatedWidgetrebuild themselves when the value of the animation changes(ex:SlideTransition)chain()to combine tweenstween.animate(CurvedAnimation)could generate animation with easing curve- extend from
SingleTicketProviderStateMixinallows state object to be aTicketProviderforAnimationController Alignment, visual coordinates, increase x move left to right.GestureDetector, handleonPanDown/onPanUpdate/onPanEnd.AnimationControllerlistenAnimationvalue to monitor animation and update positionDragEndDetailsprovide velocity of the pointer when it stopped contacing the screenAnimationController.animateWith(SpringSimulation)set the velocity of animationAnimatedContainer, when rebuilt with new properties, it automatically animates between old and new values (implicit animations)AnimatedOpacityto perform opacity animations
Test
unit test: tests a single function, method, or class.widget test(component test): tests a single widget.integration test: tests a complete app or a large part of an app.- Style
- use
flutter_testpackage WidgetTester: build and interact with widget in test environmenttestWidget(): auto-create a new WidgetTester for each test case, nad is used in place of normaltest()functions- WidgetTester’s
pumpWidgetbuilds and renders provided widgettester.pump(Duration duration): schedule a frame and trigger rebuild of widget.tester.pumpAndSettle()repeatedly callpump()with given duration until there are no longer any frames scheduled, waits for all animations to completetester.scrollUntilVisible()repeatedly scroll through lists of items until findstester.enterText(),tester.tap(),tester.drag()
- WidgetTester’s
Finderallow searching for widgets in test environmentMatcherconstant verify whether a Finder locates a widget or multiple widgets in the tets environmentfindsOneWidget,findsWidgets,findsNWidgets,matchesGoldenFile
- use
Dart Language
Dart: The language
- type safe
- static type checking, variable’s value always match variable’s static type
- use
dynamictype to combine with runtime checks - sound null safety: value can’t be null unless mention they can be
- abstract: abstract class - class can’t be instantiated. Useful for defining interfaces.
- if want abstract class to appear to be instantiable, use factory constructor
- factory: implement a constructor that doesn’t always create new instance of its class.
- ex: factory constructor might return an instance from cache, or might return an instance of subtype
- initializing a final variable using logic that can’t be handled in initializer list
- Factory constructors have no access to
this.
- stream
stream.listencould use to receive event, use it at: receive element when another progress also runningawait foruse to receive event, but it will keep waiting not end, use to eait for stream finishbroadcast(), use tolistenat multiple placessink.addto add send eventasync, the return variable will be one Stream(returnFutureelement)yield, only use insideasyncblock, could be instead ofreturn, do similar asStreamController.sink.add()
Dart: The Libraries
- dart:core: built-in types, core functionality
- dart:collection: collection types, ex: queues, linked lists, hashmaps, binary trees
- dart:convert: encoder and decoder, include JSON and UTF-8
- dart:math: mathematical constants and functions, random number generations
- dart:io file, socket, HTTP, I/O support for non-web applications
- dart:async: asynchronous program, with classes
FutureandStream - dart:typed_data: handle fixed-sized data(ex, unsigned 8-byte integers) and SIMD numeric types
- dart:ffi: foreign function interfaces for interoperability with other code that presents C-style interfaces
- dart:isolate: concurrent programming, independent workers that are similar to threads but don’t share memory, communicating only through messages
- dart:html: HTML elements and other resources for web-based applications to interact with browser and Document Object Model(DOM)
Dart: The Platforms
- Native platform: app target mobile and desktop devices, Dart includes both Dart VM(with JIT(just-in-time) compilation and AOT(ahead-of-time) compiler) for producing machine code
- during development, Dart VM offer JIT(enabling hot reload), live metrics collection, rich debugging support
- during production, Dart AOT compiler enabled compilation to native ARM or x64 machine code. AOT compiled app launches with consistent, short startup time. AOT run efficient that enforces the sound Dart type system and manages memory using fast object allocation and a generational garbage collector
- Web platform: app target web, Dart includes both
dartdevc(development time compiler) anddart2js(a production time compiler). Both compiler translate Dart into JavaScript - Dart runtime
- managing memory: Dart uses a manged memory model, where unused memory is reclaimed by a garbage collector(GC)
- enforcing Dart type system,: most type check in Dart are static(compile-time), some type checks are dynamic(runtime)
- managing isolates: Dart runtime controls the main isolate(where code normally runs) and any other isolates that app creates
First App
Practice Code: https://github.com/HevaWu/TestFlutter/tree/main/my_app
- Material is visual design language that is standard on mobile and web. Flutter offers rich set of Material widgets.
- good to set
uses-material-design: trueentry in thefluttersection underpubspec.yamlfile. This will use more features of Material, exL set of predefined icons StatelessWidget, make app itself a widget. Almost all of things in Flutter is widget, includealignment, padding, layoutScaffoldprovides defaultAppBarandbodyholds widget tree for home screen- one widget had to provide a
build()to describe how to display flutter pub add {package_name}to add package to project- perform
flutter pub getwill also auto-generatespubspec.lock Statelesswidget is immutable, properties cannot changeStatefulwidget maintain state that might change during the lifetime of the widget.- require
StatefulWidgetclass to create instance, andStateclass StatefulWidgetimmutable, can be thrown away and regeneratedStateclass persists over the lifetime of widgetstfulin IDE, use StatefulWidget template- prefix an identifier with
_enforces privacy in Dart language, recommended
- require
ListViewallow to build a list of object- when ListTile has been tapped, it will call
setState()to notify framework that state has changed
- when ListTile has been tapped, it will call
Navigatormanage stack containing the app’s routes.- push route onto Navigator’s stack updates display to that route
- pop route from Navigator’s stack return the display to previous route
MaterialPageRouteto help build route of navigation
- configure
ThemeDatato change app’s theme

Comments
Join the discussion for this article at here . Our comments is using Github Issues. All of posted comments will display at this page instantly.