簡體   English   中英

MVC+S設計中Provider模式中的NotifyListeners

[英]NotifyListeners in Provider Pattern in MVC+S Design

我正在用 MVC+S 設計開發一個 Flutter APP。 我還使用帶有 Notifylisteners 的提供者,但我經常setState() or markNeedsBuild() called during build.

使用 Providers 和 Notfylisteners 來避免這個問題的最佳實踐是什么?

我的代碼看起來像:

Class Test() {

String? testA
String? testB


FunctionA async() {
... 
testA = 'TestA';
notfifyListeners() };



FunctionB async() {
... 
testB = 'TestB';
notfifyListeners();

}

class Test extends StatefulWidget {
.
.
. 
class TestState extends State<Test> {
 @override
 voide iniState() {
  locator<TestController>().FunctionA();
  locator<TestController>().FunctionB();
  super.initState();
 }

}

.
.
.

}

您需要等待構建完成:

@override
void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      locator<TestController>().FunctionA();
      locator<TestController>().FunctionB();
    });
}

你得到異常的原因是你在嘗試構建小部件時更新 state 。

避免這種情況的最簡單方法是使用addPostFrameCallback確保 state 在初始構建后更新(這非常重要):

class TestState extends State<Test> {
 @override
 voide iniState() {
   WidgetsBinding.instance?.addPostFrameCallback((timeStamp){
      locator<TestController>().FunctionA();
      locator<TestController>().FunctionB();
    });
  super.initState();
 }

}

當您想使用具有notfifyListeners()的 function 時,請小心在您的dispose方法中使用addPostFrameCallback

快樂編碼....

不要在initState中調用提供者,因為此時您的構建器仍在進行中,並且沒有可用的BuildContext

為了避免這種情況,許多編碼人員使用Future Delaymounted來檢查 BuildContext 是否在initState中准備就緒。

但當您處理未來數據時, FutureBuilder小部件是正確的選擇。 這將在數據可用時自動構建小部件,您無需檢查mounted

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM