'How to set BLOC initial value as last value of a counter
here I'm trying to save the last value of the counter app using SharedPreference.
here look at the initial value of bloc state
part of 'counter_bloc.dart';
class CounterState {
final int count;
CounterState({required this.count});
}
//initial counter
class InitialCounter extends CounterState {
InitialCounter() : super(count: 0,);
}
here is the sharedPref saving code
onSaved(_counter)async{
final pref = await SharedPreferences.getInstance();
await pref.setInt('counter', _counter);
}
and here is the code of counter text widget code
Center(
child: BlocBuilder<CounterBloc, CounterState>(
builder: (context, state) {
return Padding(
padding: const EdgeInsets.only(top: 40),
child: GestureDetector(
onTap: () =>
context.read<CounterBloc>().add(CounterIncrement()),
child: Text(
'${state.count}',
style: TextStyle(
fontSize: state.count > 999 ? 80 : 120,
color: type == Type.darkMode
? kDarkCounterColor
: kLightCounterColor,
fontFamily: 'Latino'),
),
));
},
),
);
and here is my question
currently, when we get the app the counter value will be 0. because we set that as 0 in bloc state code. but I want to show the last saved number and increment from there. how can I do that?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
