1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Memory leak when using setState to overwrite value flutter

Discussão em 'Mobile' iniciado por Stack, Setembro 10, 2024.

  1. Stack

    Stack Membro Participativo

    I have some problem. When I try to overwrite a value using setState, infinite loop happening and a warning about memory leaks. I dont know why its happening, and I tried to put if(mounted), but its still not working. Any advice for this?

    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)";
    });
    });
    }
    }
    )


    This ListView is inside an AlertDialog that wrapped in StatefullBuilder so it can update the view when setState is called.

    This is the error log

    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().

    Continue reading...

Compartilhe esta Página