Printing Counter variable value but Value Difference between print() and UI. while using Timer() and riverpod

76 views Asked by At

In Flutter, I am trying to build a counter that increments only until i hold down the button. I have done it, but why is there value difference between within Terminal and in the UI. (see picture) I am using riverpod to update the UI.

I checked putting print() just before ref.read(myprovider.notifier).state ++

my full code is:



class StateProviderPond extends ConsumerWidget {
  static const String page_id = 'goto_state';

  int counter_int = 90001;

  Timer? timerCounter;

  StateProviderPond({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    counter_int = ref.watch(myStateProviderInt);

    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.transparent,
        title: const Text('riverpod-state provider'),
        centerTitle: true,
        actions: [
          IconButton(onPressed: () {}, icon: Icon(Icons.arrow_back_ios))
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Text(
              '$counter_int',
              style: TextStyle(fontSize: 50, color: Colors.white38),
            ),
            Column(
              children: [
                GestureDetector(
                  child: Center(
                    child: Text('~',
                        style: TextStyle(fontSize: 30, color: Colors.indigo)),
                  ),
                  onTapDown: (TapDownDetails details) {
                    print('down');
                    // timer?.cancel();
                    timerCounter =
                        Timer.periodic(Duration(milliseconds: 1), (t) {
                      print(counter_int++);
                      ref.read(myStateProviderInt.notifier).state++;
                    });
                  },
                  onTapUp: (TapUpDetails details) {
                    timerCounter?.cancel();
                    print('up');
                    print('***********');
                  }, 
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

enter image description here

1

There are 1 answers

2
Jakhongir Anasov On BEST ANSWER

Because print(counter++); firstly prints the value, then increment it. You should do print(++counter); Here you can see simple dart cli to explain this behaviour. enter image description here