3
Hello, good afternoon!
I am trying to make a checkbox list (Checkboxlisttile) using mobx, however, whenever I click on the box to mark or deselect I have to use the flutter Reload or setState to update the data.
mobx is not automatically updating using Observer, I don’t know why. Could you help me?
My model:
part 'ItemComplementoModel.g.dart';
class ItemComplementoModel = _ItemComplementoModel with _$ItemComplementoModel;
abstract class _ItemComplementoModel with Store{
@observable
ObservableList<Map<String, dynamic>> listaItens = ObservableList<Map<String, dynamic>>();
@action
void addItem(Map<String, dynamic> novoItem){
listaItens.add(novoItem);
}
@action
void marcarItem(int indice, bool marcou, ItemComplemento itemComplemento){
print("marcou");
//listaItens[indice]["marcou"] = marcou;
print(listaItens);
print("depois...");
listaItens[indice]["marcou"] = marcou;
print(listaItens);
}
}
My Observer:
_parteItemComplemento(int indice, ItemComplemento itemComplemento){
return Observer(
builder: (_){
return CheckboxListTile(
onChanged: (marcou){
//setState(() {
//_listaItensComplementos[indice]["marcou"] = marcou;
itemComplementoModel.marcarItem(indice, marcou, itemComplemento);
print("marcou: ${marcou}");
//_saveData();
//});
},
title: Text(itemComplemento.nome),
//value: _listaItensComplementos[indice]["marcou"],
value: itemComplementoModel.listaItens[indice]["marcou"],
secondary: CircleAvatar(
child: Icon(
itemComplementoModel.listaItens[indice]["marcou"]
? Icons.check
: Icons.error
),
),
);
},
);
}
If you’re using the Mobx it is not necessary to use the setState()... Your problem, I believe, taking a look at it, I think it’s because you’re using a Observablelist of the kind Map, the list is updated when the reference of an object of it changes, and in your case you are only changing a value of an object of the Map, thus the reference of the same does not change. If you change the marcarItem, for example, to:
listaItens[indice] = {"marcou": false};
orlistaItens[indice] = {"marcou": true};
should work.– Matheus Ribeiro
Perfect! Problem solved, thank you very much.
– Alex Anderson
I got a little time to produce a more detailed answer! From a look later.
– Matheus Ribeiro