Internalization
- add
flutter_localizations
package as dependency - add
intl
package dependency - add
generate: true
underpubspec.yaml - flutter
- add
l10n.yaml
- with
arb-dir
,template-arb-file
,output-localization-file
- with
- provides localized strings and values for library
GlobalMaterialLocalizations.delegate
GlobalWidgetsLocalizations.delegate
Locale
language code entries in IANA Language Subtag RegistryLocalizations.localOf()
get app current locale
Networking
Test project:
Notes:
http
pakcage, composable and Future-based library for making HTTP requestFuture
is core Dart class for working with async operations. Future object represents potential value/error thatwill be available at some time in the futurehttp.Response
contains data received from a successful http callFutureBuilder
widget to display data on screensnapshot.hasData
only returnstrue
when 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_serializable
andbuilt_value
json_serializable
allow to make regular classes serializing by using annotationsbuilt-value
provides 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 RenderBox
return aRenderBox
to tell where the item areAlignment.inscribe()
return rect of the given size, aligned within given rect as specifiedImage
can apply filters withcolor
andcolorBlendMode
LayoutBuilder
: 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 allowsIgnorePointer
widget is invisible when hit, disable interactionClipOval
: widget clip with ovalScrollable
ListView
widget always position first element at beginning of available space.PageView
widget layout children from the center of the available space, and provides snapping physics.PageController
hasviewportFraction
used to display multiple item on screen at the same time- can
addListener
to controller, monitor changes - use
hasClients
andposition.hasContentDimensions
to check if there is PageView and PageController is attached animateToPage
move that item into center
- can
Flow
, can control transform of a child widget immediately before widget paint, control where child is paintedFlowDelegate
control 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
Scrollable
withviewportBuilder
, placeFlow
widget inside theviewportBuilder
. TheFlow
has adelegate property
that allows position child widget wherever we want, based on currentviewportOffset
ValueNotifier
notify when value changedValueListenableBuilder
could use to listen this notifier
BoxFit
how to fit another box, ex: contain, coverAlwaysStoppedAnimation
animation always stop at one timeChangeNotifier
A class that can be extended or mixed in that provides a change notification API using VoidCallback for notifications.notifyLiseners()
notify changes
Navigator
widget to handle top-level navigation flowMaterialPageRoute<dynamic>
construct MaterialPageRoute whose contents are defined by builderNavigatorState
, the state for Navigator widget
GlobalKey
is 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
AppBar
andTabBar
, widget needs to expose a preferred or default size
- for
WillPopScope
calback when user attempts to dismiss the enclosing ModalRouteAlertDialog
to 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
)StatefulWidget
contains 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
AppBar
to show it - use
Navigator.pop(context)
to close drawer. When user open a drawer(menu), Flutter add drawer to navigation stack.
- need a
Scaffold
from material library, ensure widget won’t overlapSnackBar
, can add action byaction: SnackBarAction
ScaffoldMessenger.of
could use to show SnackBarOrientationBuilder
: build different layout on landscape or portrait- use
MediaQuery.of(context).orientation
could get orientation of the screen - Flutter supports
.ttf
and.otf
font 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 themeTabController
build a tabbar controllerTabBar(tabs:[])
create each tabBarItembody: TabBarView(children:)
create each tabBar content view
Animation
Test project:
Notes:
PageRouteBuilder
provideAnimation
object- Animation can be used with
Tween
andCurve
object to customize the transition animation child
param in transitionBuilder is widget returned from pageBuilder.pageBuilder
only called the first time the route is built. Framework can avoid extra work becausechild
stays the same throughout the transition.
- Animation can be used with
FractionalTranslation
, apply translation transformation before painting its childAnimatedWidget
rebuild themselves when the value of the animation changes(ex:SlideTransition
)chain()
to combine tweenstween.animate(CurvedAnimation)
could generate animation with easing curve- extend from
SingleTicketProviderStateMixin
allows state object to be aTicketProvider
forAnimationController
Alignment
, visual coordinates, increase x move left to right.GestureDetector
, handleonPanDown/onPanUpdate/onPanEnd
.AnimationController
listenAnimation
value to monitor animation and update positionDragEndDetails
provide 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)AnimatedOpacity
to 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_test
package 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
pumpWidget
builds 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
Finder
allow searching for widgets in test environmentMatcher
constant 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
dynamic
type 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.listen
could use to receive event, use it at: receive element when another progress also runningawait for
use to receive event, but it will keep waiting not end, use to eait for stream finishbroadcast()
, use tolisten
at multiple placessink.add
to add send eventasync
, the return variable will be one Stream(returnFuture
element)yield
, only use insideasync
block, 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
Future
andStream
- 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: true
entry in theflutter
section underpubspec.yaml
file. 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, layout
Scaffold
provides defaultAppBar
andbody
holds 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 get
will also auto-generatespubspec.lock
Stateless
widget is immutable, properties cannot changeStateful
widget maintain state that might change during the lifetime of the widget.- require
StatefulWidget
class to create instance, andState
class StatefulWidget
immutable, can be thrown away and regeneratedState
class persists over the lifetime of widgetstful
in IDE, use StatefulWidget template- prefix an identifier with
_
enforces privacy in Dart language, recommended
- require
ListView
allow 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
Navigator
manage 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
MaterialPageRoute
to help build route of navigation
- configure
ThemeData
to 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.