Closed amaury901130 closed 2 years ago
Recommended libraries:
Counter example:
class Counter extends ChangeNotifier {
int count = 0;
void increment() {
count += 1;
notifyListeners();
}
}
class MyApp extends ConsumerWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Example')),
body: Center(
child: Consumer<Counter>(
builder: (context, counter, child) {
return Text("${counter.count}");
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => Provider.of<Counter>(context, listen: false).increment(),
child: const Icon(Icons.add),
),
),
);
}
}
Counter example:
final counterProvider = StateProvider((_) => 0);
class MyApp extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
//Watch the changes on the provider
final String value = ref.watch(counterProvider);
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Example')),
body: Center(
child: Text(counterProvider),
),
floatingActionButton: FloatingActionButton(
// The read method is a utility to read a provider without listening to it
onPressed: () => ref.read(counterProvider.notifier).state++,
child: const Icon(Icons.add),
),
),
);
}
}
Counter example:
abstract class CounterEvent {}
class Increment extends CounterEvent {}
class CounterBloc extends Bloc<CounterEvent, int> {
CounterBloc() : super(0) {
on<Increment>((event, emit) => emit(state + 1));
}
}
class CounterPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: BlocBuilder<CounterBloc, int>(
builder: (context, count) {
return Text('$count');
},
),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () => context.read<CounterBloc>().add(Increment()),
),
);
}
}
Counter example:
enum Actions { Increment }
int counterReducer(int state, dynamic action) {
return action == Actions.Increment ? state + 1 : state;
}
void main() {
final store = Store<int>(counterReducer, initialState: 0);
runApp(
Home(
title: 'Flutter Redux Demo',
store: store,
),
);
}
class Home extends StatelessWidget {
final Store<int> store;
final String title;
Home({Key key, this.store, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return StoreProvider<int>(
store: store,
child: MaterialApp(
theme: ThemeData.dark(),
title: title,
home: Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(
child: StoreConnector<int, String>(
converter: (store) => store.state.toString(),
builder: (context, count) {
return Text('$count');
},
),
),
floatingActionButton: StoreConnector<int, VoidCallback>(
converter: (store) {
return () => store.dispatch(Actions.Increment);
},
builder: (context, callback) {
return FloatingActionButton(
onPressed: callback,
child: Icon(Icons.add),
);
},
),
),
),
);
}
}
Examples here: https://github.com/amaury901130/sample_flutter_state