flutter 需要清楚了解StateFull小部件dispose()方法

gj3fmq9x  于 2022-12-19  发布在  Flutter
关注(0)|答案(1)|浏览(162)

I have a counter app with 2 buttons. One for reset to 0, other for incrementing. Now I want to store the count value. So when I close it and open again, it will show the last count value. I tried get_storage but it is not working as I expected. If I put save_logic inside "onpressed" of the button, then it works fine. [ Because each time when the button is pressed, we are storing fresh value of count variable ]. But if I put save_logic inside dispose(), it doesn't work.


[ It should work because as far as I know it will be called just before the StateFull widget is destroyed or removed from widgets_tree ]. [ Interesting confusion is - I tried it before and I remembered that worked. Then I deleted the project thinking I understood it but now I am confused 🙁 ]

bnl4lu3b

bnl4lu3b1#

GetStorageasync调用,就像您在initState中所做的那样,您应该await它。但是,由于disposesync,因此最好在每次按下incrementdecrement按钮时更新存储中的值

@override
  Future<void> dispose() async {
    Future.delayed(Duration.zero, () async {
        //do your storage here
      await WriteYourValuesHere("value");
    });
    super.dispose();
  }

相关问题