Flutter生命周期超詳細講解
一 這里看一下StatefulWidget的生命周期
其本身是由兩個類組成的,StatefulWidget 和 State 組成的。
class DemoWidget extends StatefulWidget { const DemoWidget({super.key}); @override State<DemoWidget> createState() => _DemoWidgetState(); } class _DemoWidgetState extends State<DemoWidget> { @override Widget build(BuildContext context) { return Container(); } }
首先
會執(zhí)行StatefulWidget 中相關(guān)的方法
* 1 執(zhí)行StatefulWidget的構(gòu)造函數(shù)(Constructor)來創(chuàng)建StatefuleWidget
* 2 執(zhí)行StateWidget的createState 方法,來創(chuàng)建一個維護StatefulWidget 的State對象
其次
調(diào)用createState 創(chuàng)建State對象時候,執(zhí)行State類相關(guān)的方法
* 1 執(zhí)行State 類的構(gòu)造方法(Constructor)來創(chuàng)建State 對象
* 2 執(zhí)行initState,我們通常會在這個方法中執(zhí)行一些數(shù)據(jù)初始化的操作或者也可能發(fā)送數(shù)據(jù)請求
@override void initState() { super.initState(); }
* 3 執(zhí)行didChangeDependencies 方法,這個方法會在兩種情況下調(diào)用
- 調(diào)用initState 會調(diào)用
- 從其他對象依賴一些數(shù)據(jù)發(fā)生改變的時候,會調(diào)用
* 4 執(zhí)行build 方法,來看一下當前的widget 需要渲染哪些Widget,構(gòu)建對應(yīng)的widgets
* 5 當前的widget 不再使用的時候,會調(diào)用dispose 進行銷毀
* 6 手動調(diào)用setState方法,會根據(jù)最新的狀態(tài)(數(shù)據(jù)) 開重新調(diào)用build 方法,構(gòu)建對應(yīng)的Widgets
* 7 執(zhí)行didUpdateWidget 方法是當父Widget 觸發(fā)重建(rebuild)時,系統(tǒng)會調(diào)用didUpdateWidget方法
二 SetState
/// Marks the element as dirty and adds it to the global list of widgets to /// rebuild in the next frame. /// /// Since it is inefficient to build an element twice in one frame, /// applications and widgets should be structured so as to only mark /// widgets dirty during event handlers before the frame begins, not during /// the build itself. void markNeedsBuild() { void scheduleBuildFor(Element element) if (_dirty) { owner!.scheduleBuildFor(this); } if (hadDependencies) { didChangeDependencies(); } } /// Adds an element to the dirty elements list so that it will be rebuilt /// when [WidgetsBinding.drawFrame] calls [buildScope]. void scheduleBuildFor(Element element) { }
setState的調(diào)用 其實是element 會調(diào)用 markNeedsBuild 這個方法,標記當前的element 需要更新。dirty 設(shè)置為true.
方法的最后會調(diào)用一個BuildOwner類中的
scheduleBuildFor 方法,這個方法注釋寫的很清楚,就是吧這個element 添加到dirty elements list 中去,當WidgetsBinding.drawFrame 去走更新的流程
when [WidgetsBinding.drawFrame] calls [buildScope].
到此這篇關(guān)于Flutter生命周期超詳細講解的文章就介紹到這了,更多相關(guān)Flutter生命周期內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android之Viewpager+Fragment實現(xiàn)懶加載示例
本篇文章主要介紹了Android之Viewpager+Fragment實現(xiàn)懶加載示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03android studio xml文件實現(xiàn)添加注釋
這篇文章主要介紹了android studio xml文件實現(xiàn)添加注釋,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03Android10 App 啟動分析進程創(chuàng)建源碼解析
這篇文章主要為大家介紹了Android10 App啟動分析進程創(chuàng)建源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10