addPostFrameCallback
用法:addPostFrameCallback
回調(diào)方法在Widget渲染完成時(shí)觸發(fā),所以一般我們?cè)讷@取頁(yè)面中的Widget大小、位置時(shí)使用到。
? 若我們?cè)诮涌谡?qǐng)求前彈出loading。例如我將請(qǐng)求方法放在了initState方法中,可能出現(xiàn)的異常如下:
inheritFromWidgetOfExactType(_InheritedTheme) or inheritFromElement() was called before initState() completed.
When an inherited widget changes, for example if the value of Theme.of() changes, its dependent widgets are rebuilt. If the dependent widget’s reference to the inherited widget is in a constructor or an initState() method, then the rebuilt dependent widget will not reflect the changes in the inherited widget.
Typically references to inherited widgets should occur in widget build() methods. Alternatively, initialization based on inherited widgets can be placed in the didChangeDependencies method, which is called after initState and whenever the dependencies change thereafter.
? 所以我們需要在build完成后,才可以去創(chuàng)建這個(gè)新的組件(這里就是Dialog)忿檩。
? 所以解決方法就是使用addPostFrameCallback回調(diào)方法,等待頁(yè)面build完成后在請(qǐng)求數(shù)據(jù):
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_){
/// 接口請(qǐng)求
});
}
? 導(dǎo)致這類問(wèn)題的場(chǎng)景很多爆阶,但是大體解決思路就是上述的辦法燥透。