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('***********');
},
),
],
),
],
),
),
);
}
}
Because
print(counter++);
firstly prints the value, then increment it. You should doprint(++counter);
Here you can see simple dart cli to explain this behaviour.