使用setState覆盖值flutter时内存泄漏

问题描述 投票:0回答:1

我有一些问题。当我尝试使用 setState 覆盖值时,会发生无限循环并出现有关内存泄漏的警告。我不知道为什么会发生这种情况,我尝试添加

if(mounted)
,但它仍然不起作用。对此有什么建议吗?

    ListView.separated(
      separatorBuilder: (BuildContext context, int i) => Divider(color: Colors.grey[400]),
      itemCount: listJadwalDokter.length,
      itemBuilder: (context, index) {
          JadwalDokter jadwal = listJadwalDokter[index];
          if(jadwal.hari < now.weekday)
             for(int test = 0;test <jadwal.jadwalPraktek.length; test++) {
                cutiService.cekCuti(jadwal.kodeDokter + "." + listTanggalFormatKode[jadwal.hari + 7] + jadwal.jadwalPraktek[test].jam.substring(0, 2)).then((value) {
                     if (value)
                        if(mounted)
                          setState(() {
                               //when infinite loop happened
                             jadwal.jadwalPraktek[test].jam =jadwal.jadwalPraktek[test].jam.substring(0, 11) + "\n(Sedang Cuti)";
                          });
                 });
             }
       }
   )

这个

ListView
位于包含在
AlertDialog
中的
StatefullBuilder
中,因此它可以在调用 setState 时更新视图。

这是错误日志

E/flutter ( 6791): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
E/flutter ( 6791): The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter ( 6791): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().

         
flutter flutter-layout
1个回答
0
投票

最新版本修复了setState()造成的内存泄漏问题。 如果仍有问题,请将频道更改为 Master 并重试。

flutter upgrade
flutter channel master
© www.soinside.com 2019 - 2024. All rights reserved.