Mobx flutter observable is not updating the value. Every time I am getting default value

3.2k Views Asked by At

Hello I am new to flutter and I am trying to use mobx state management.

import 'package:mobx/mobx.dart';
part 'counter.g.dart';

class Counter = _Counter with _$Counter;

abstract class _Counter with Store {
  @observable
  String hello = 'Hello';

  @action
  void changeName(_name){
    hello = _name;
  }
}

and .g.dart also generated with updated values. I am firing the action like (Action calling part)

final Counter counter = Counter();

return Observer(builder: (_)=> InkWell(
            onTap: () {
              counter.changeName("updated value");
    }.....something like this.

Rendering part:

final Counter counter = Counter();
 return Scaffold(
      body: Observer(builder: (_) {
        return Container(
          height: 100.0,
          width: 100.0,
          decoration: BoxDecoration(),
          child: Text(counter.hello),
        );
      }),

Everytime I am getting counter.hello as "Hello"(Default value). I am not getting "Updated Value"

-> Action changeName is triggering (I have debugged it)

Please help me.

1

There are 1 best solutions below

1
On

This part

final Counter counter = Counter();

return Observer(builder: (_)=> InkWell(
        onTap: () {
          counter.changeName("updated value");
}

and this part

final Counter counter = Counter();
 return Scaffold(
  body: Observer(builder: (_) {
    return Container(
      height: 100.0,
      width: 100.0,
      decoration: BoxDecoration(),
      child: Text(counter.hello),
    );
  }),

are in the same widget tree ? I noticed that in both parts you instantiate the Counter(), for the text to update, you need to use the same instance of the class.