《2019年快速掌握Flutter开发核心技能.pdf》由会员分享,可在线阅读,更多相关《2019年快速掌握Flutter开发核心技能.pdf(86页珍藏版)》请在三个皮匠报告上搜索。
1、?Flutter?Flutter?&?Flutter?&?Dart?1.?&?2.?3.?Flutter?Flutter?-?&?UI?Native?Flutter?-?UICard(child:Container(child:Row(children:Container(width:90,height:90,child:Image.asset(assets/poi.png),),Expanded(child:Column(crossAxisAlignment:,children:titleRow,scoreRow,distanceRow,)?/?b.setColor(red)b.clearC
2、hildren()ViewC c3=new ViewC(.)b.add(c3)/?return ViewB(color:red,child:ViewC(.),)?Flutter?-?UICard(child:Container(child:Row(children:Container(width:90,height:90,child:Image.asset(assets/poi.png),),Expanded(child:Column(crossAxisAlignment:,children:titleRow,scoreRow,distanceRow,)?/?b.setColor(red)b.
3、clearChildren()ViewC c3=new ViewC(.)b.add(c3)/?return ViewB(color:red,child:ViewC(.),)?!?Flutter?-?UICard(shape:RoundedRectangleBorder(),elevation:2,child:Container(padding:const EdgeInsets.fromLTRB(15,15,15,15),child:Row(crossAxisAlignment:CrossAxisAlignment.start,children:Container(width:90,height
4、:90,padding:child:Image.asset(assets/poi.png),),Expanded(child:Column(crossAxisAlignment:CrossAxisAlignment.start,children:titleRow,scoreRow,distanceRow,Divider(height:1,color:Colors.black38,),groupBuySection,)CardRowImageColumntitlescore location?Flutter?-?Flutter?-?Flutter?&?Native?pub client?Flut
5、ter?#?Flutter?UI?App?Flutter?UI?OEM OS?Flutter?dart:ui?Flutter Framework?Dart?Engine?Engine?Native?Flutter?Embedder?Flutter?UI?Widget?Gesture?Animation?Router?Assets?Flutter?Graphics PipelineRendering Pipeline?Flutter?-LayoutConstraintsSizes?Width?Height print(Tapped),child:Text(Hello World),),),);?
6、GestureDetector?GestureDetector?Flutter?-?&?Widget?!?Flutter?-?&?Widget?Element?Widget?RenderObject?(render tree)?Flutter?-?&?runApp(myApp()myApp:WidgetrenderViewElementrenderView:RenderObjectvoid runApp(Widget app)WidgetsFlutterBinding.ensureInitialized().attachRootWidget(app).scheduleWarmUpFrame()
7、;void attachRootWidget(Widget rootWidget)_renderViewElement=RenderObjectToWidgetAdapter(container:renderView,debugShortDescription:root,child:rootWidget ).attachToRenderTree(buildOwner,renderViewElement);scheduleFrame()?Flutter?-?&?WidgetElementRenderObjectmount()createElement()build()inflateWidget(
8、)mount()ComponentElementperformBuild()inflateWidget()createElement()RenderObjectElementmount()createRenderObject()attachRenderObject()adoptChild()?Flutter?-?Flutter?-?class MyHomePage extends StatefulWidget MyHomePage(Key key,this.title):super(key:key);final String title;override _MyHomePageState cr
9、eateState()=_MyHomePageState();class _MyHomePageState extends State int _counter=0;void _incrementCounter()setState()_counter+;);override Widget build(BuildContext context)return Scaffold(appBar:AppBar(title:Text(widget.title),),body:Center(child:Column(children:Text(You have pushed the button this
10、many times:$_counter,),),),floatingActionButton:FloatingActionButton(onPressed:_incrementCounter,child:Icon(Icons.add),),);?Flutter?-?UI=f()?build?state?Other Events?setSate?Flutter?-?Flutter?-?class Counter with ChangeNotifier int _counter;Counter(this._counter);getCounter()=_counter;setCounter(int
11、 counter)=_counter=counter;void increment()_counter+;notifyListeners();void decrement()_counter-;notifyListeners();State?Flutter?-?class MyApp extends StatelessWidget override Widget build(BuildContext context)return MaterialApp(title:Flutter Demo,theme:ThemeData(primarySwatch:Colors.blue,),home:Cha
12、ngeNotifierProvider(builder:(_)=Counter(0),child:HomePage(),);?State?Flutter?-?class HomePage extends StatelessWidget override Widget build(BuildContext context)final counter=Provider.of(context);return Scaffold(appBar:AppBar(title:Text(Provider Demo),body:Center(child:Column(mainAxisAlignment:MainA
13、xisAlignment.center,children:Text(You have pushed the button this many times:),Text($counter.getCounter(),style:Theme.of(context).textTheme.display1,),?State?Flutter?-?floatingActionButton:Column(mainAxisAlignment:MainAxisAlignment.end,children:FloatingActionButton(onPressed:counter.increment,toolti
14、p:Increment,child:Icon(Icons.add),),SizedBox(height:10),FloatingActionButton(onPressed:counter.decrement,tooltip:Increment,child:Icon(Icons.remove),),),?Flutter?-?UI=f()?build?state_counterinc()dec()ProviderHomePageTextButtonCounter?State?State?State?&?build()?Flutter?-?State?State?!?Flutter?-?RTIMa
15、p _provider:elementElement tree._Provider_provider.T valueInheritedWidgetinflateWidget()Provider.of(context)Provider.value(value:counter,)mount()mount()Map _provider:elementcontext.inheritFromWidgetOfExactType(type)type=_Provider?Flutter?-?!?Flutter?-?EventsStatesStreamsBLoCBLoCDelegatee4e3e2e1s4s3s
16、2s1StreamsonEvent()onTransition()onError()dispatch(e)Transitions?StatemapEventToState(event)?TransitionsTransitions?Flutter?-?ActionReducerStoreViewMStoreProviderSPStoreConnectorSCTBstreamonPressedStreamBuilder-store-converter-builder?get?v=c(d)converted_stream?map(converter)?reducer?data?value?valu
17、e?listen?action?Flutter?-?!?State?:https:/ Space Scavenger1.?Young Space Scavenger2.?Mark-Sweep3.?Flutter Engine Idle Notification4.isolate?heapNo Impact with others?Dart?-?1.future,async&await2.stream3.isolate?Dart?-futureFuture?:Uncompleted or CompletedFuture getWeather()return Future.delayed(Dura
18、tion(seconds:4),()print(?););main()getWeather();print(?);!?Dart?-futureFuture?:Uncompleted or CompletedFuture getWeather()return Future.delayed(Duration(seconds:4),()print(?););main()getWeather();print(?);?uncompleted future?Dart?-async&awaitasync:?function?await:?async function?Future getWeather()r
19、eturn Future.delayed(Duration(seconds:4),()print(?););main()async await getWeather();print(?);!?Dart?-async&awaitasync:?function?await:?async function?Future getWeather()return Future.delayed(Duration(seconds:4),()print(?););main()async await getWeather();print(?);?await an uncompleted future instan
20、ce?future complete?Dart?-future,async&await?Event LoopEvent Loop?Event Loopmain?main?Dart?-future,async&awaitmain()print(Future?);Future()print(?Future);)print(Future?);Future?Future?Future?Future?Future?Future?future?task?Event Queue?uncompleted futureEvent Loopvoid main()async print(A);await metho
21、dB();await methodC(main);print(D);methodB()async print(B start);await methodC(B);print(B end);methodC(String from)async print(C start from$from);Future()print(C running Future from$from);).then(_)print(C end of Future from$from););print(C end from$from);1.A2.B start3.C start from B4.C end from B5.B
22、end6.C start from main7.C end from main8.D9.C running Future from B10.C end of Future from B11.C running Future from main12.C end of Future from main!?Dart?-future,async&awaitasync?1.?future2.?await future3.?await future?future?1.await?await future?2.async?event loop?void main()async print(A);await
23、methodB();await methodC(main);print(D);methodB()async print(B start);await methodC(B);print(B end);methodC(String from)async print(C start from$from);await Future()print(C running Future from$from);).then(_)print(C end of Future from$from););print(C end from$from);1.A2.B start3.C start from B4.C run
24、ning Future from B5.C end of Future from B6.C end from B7.B end8.C start from main9.C running Future from main10.C end of Future from main11.C end from main12.D?Dart?-streamFuture sumStream(Stream stream)async var sum=0;await for(var value in stream)sum+=value;return sum;stream:?sunmStream?isolateMu
25、tator ThreadHelper ThreadHeap?Dart?-isolate?isolate?mutator?Dart?isolate?helper?GC,JIT?isolate?heap?1.?“thread”2.?event loop3.?isolate-?isolateMutator ThreadHelper ThreadHeapisolateMutator ThreadHelper ThreadHeapportmessagevm isolateHeap?isolate?null,true,false?isolate-?1.isolate.spawn2.isolate?pute
26、()?!?isolate-isolate.spawnisolate1isolate2isolate.spawn-entryPoint(T Message)-message?Port?entryPointresultreceivePortsendPort?isolate-?void isoEntry(List message)SendPort replyPort=message0;int result=loop(message1);replyPort.send(result);void isolateDemo()RawReceivePort reply=new RawReceivePort();
27、reply.handler=(count)print(?:$count);reply.close();Isolate.spawn(isoEntry,reply.sendPort,100);1.?isolate3.isolate?2.isolate?isolate-isolate.spawnisolate1isolate2sendPort2receivePort2receivePort1sendPort1?spawn msg?sendPort?isolate-?void isoEntry(sendPort1)RawReceivePort receivePort2=new RawReceivePo
28、rt();receivePort2.handler=(v)sendPort1.send(loop(v);receivePort2.close();sendPort1.send(receivePort2.sendPort);void isolateDemo()RawReceivePort receivePort1=new RawReceivePort();var completer=new Completer();receivePort1.handler=plete;Isolate.spawn(isoEntry,receivePort1.sendPort).then(Isolate iso)re
29、turn completer.future;).then(sendPort2)sendPort2.send(24);receivePort1.handler=(count)print(?:$count);receivePort1.close(););?spawn msg?sendPort?isolate-?void isolateDemo()RawReceivePort receivePort1=new RawReceivePort();Isolate isolate;Capability resume;var completer=new Completer();receivePort1.ha
30、ndler=plete;Isolate.spawn(isoEntry,receivePort1.sendPort).then(Isolate iso)isolate=iso;return completer.future;).then(sendPort2)resume=isolate.pause();sendPort2.send(24);receivePort1.handler=(count)throw?;return new Future.delayed(const Duration(milliseconds:250);).then(_)receivePort1.handler=(v)if(
31、v!=24)throw?!;receivePort1.close();isolate.resume(resume););?isolate-?Future compute(ComputeCallback callback,Q message,String debugLabel)int heavyJob(int val)/?Future runByCompute()async int result=await compute(heavyJob,100000);print(result);1.?isolate2.?message?callback3.?callback?Dart?-?(Dart Na
32、tive)Just-in-Time(JIT)Ahead-of-Time(AOT)sourcefilesmachinecodeCPU archruntimesourcefilesILCPU archVMsourcefiles?Dart?Just-in-Time(JIT)Ahead-of-Time(AOT)?!?Dart?“Dart VM”kernel binaryJITsnapshotAOT(app-jit&app-aot)?Dart?-kernel binary/hello.dart main()=print(Hello,MPD!);$dart hello.dart Hello,MPD!?!?
33、Dart?-kernel binaryDart SourceCFEVMdart front endKernel AST(.dill?)KernelBinarymain isolate?Kernel AST(.dill?)KernelBinaryVM objects?classefieldfunction?Dart?-kernel binary$dart pkg/vm/bin/dump_kernel.dart hello.dill hello.kernel.txt main=hel:main;library from“file:/a/b/c/demos/hello.dart”as hel sta
34、tic method main()dynamic return core:print(Hello,World!);library dart.async from dart:async as asy import dart:_internal;import dart:collection;part async_error.dart;part broadcast_stream_controller.dart;.?Dart?-kernel binaryDart SourceKernel AST(.dill?)KernelBinaryflutter run debugfrontend_server(C
35、FE)HostDeviceFlutter EngineVM?Dart?-app-jit snapshot/hello.dart main()=print(Hello,MPD!);$dart snapshot=hello.appjit.snapshot-snapshot-kind=app-jit hello.dart Hello,MPD!?!?Dart?-app-jit snapshot?Dart?-app-jit snapshot$strings hello.appjit.snapshot EventHandler_SendData _sendData15069316 EventHandler
36、_TimerMillisecondClock _timerMillisecondClock15069316 _EventHandler15069316._EventHandler _EventHandler15069316 dart.asyncVMLibraryHookspatchHashMapIterableBaseCastStreamCastStreamTransformerEmptyIteratorIterableElementErrorprintToZoneprintToConsoleSinceasync_error.dartbroadcast_stream_controller.da
37、rtdeferred_load.dartfuture.dartfuture_impl.dartschedule_microtask.dartstream.dartstream_controller.dartstream_impl.dartstream_pipe.dartstream_transformers.darttimer.dartzone.dart_ScheduleImmediateClosurecallback_TimerFactoryClosuremillisecondsrepeating_FutureOnValueSTvalue_FutureErrorTesterror_Futur
38、eAction_AsyncCallback_TimerCallbackControllerCallbackControllerCancel?Dart?-app-aot snapshot/hello.dart main()=print(Hello,MPD!);$dart2aot hello.dart hello.dart.aot$dartaotruntime hello.dart.aot Hello,MPD!?!?Dart?-app-aot snapshotCFEdart front endKernel BinaryDart SourceKernel BinaryKernel BinaryTFA
39、unreachablemethodstype flow analysisVMILASMAOT snapshotgenSnapshotdart runtime#Step 1:Generate Kernel binary from the input Dart source.$BIN_DIR/dart$SDK_DIR/pkg/vm/bin/gen_kernel.dart -platform$BIN_DIR/vm_platform_strong.dill -aot$GEN_KERNEL_OPTIONS$PACKAGES -o$SNAPSHOT_FILE.dill “$SOURCE_FILE#Step
40、 2:Generate snapshot from the Kernel binary.$BIN_DIR/gen_snapshot -snapshot-kind=app-aot-assembly -assembly=$SNAPSHOT_FILE.S$OPTIONS$SNAPSHOT_FILE.dill#Step 3:Assemble the assembly file into an ELF object.if$BUILD_ELF-eq 1;then gcc-shared-o$SNAPSHOT_FILE$SNAPSHOT_FILE.S fi?Dart?-app-aot snapshot1.?k
41、ernel binary2.kernel binary-?3.?-shared librarypkg/vm/tool/precompiler2?Dart?-?flutter build aotAndroid:flutter.gradleproject.exec executable flutterExecutable.absolutePath workingDir sourceDir args build,aot args-target,targetPath args“-target-platform,android-arm args-output-dir,“$intermediateDir”
42、args“-$buildModeflutter build bundleiOS:xcode_backend.sh RunCommand$FLUTTER_ROOT/bin/flutter$verbose_flag build bundle -target-platform=ios -target=$target_path -$build_mode -depfile=$build_dir/snapshot_blob.bin.d asset-dir=“$derived_dir/xx/flutter_assets$precompilation_flag releasedebugAOTJITapp.dillApp.framework snapshot_data snapshot_instrFrontendServerGenSnapshot?