Skip to content

Instantly share code, notes, and snippets.

@MariaMelnik
Last active August 18, 2022 10:18
Show Gist options
  • Save MariaMelnik/52718723e18657399ec3896b6ad23493 to your computer and use it in GitHub Desktop.
Save MariaMelnik/52718723e18657399ec3896b6ad23493 to your computer and use it in GitHub Desktop.
flutter: check bloc updates
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
final state = MyState();
final cubit = MyCubit(state);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//
// create
//
BlocProvider(
// key: UniqueKey(),
create: (_) => MyCubit(state),
child: BlocConsumer<MyCubit, MyState>(
listener: (context, state) {},
builder: (context, state) {
return Text('state1 is $state (${state.hashCode})');
},
),
),
//
// value
//
BlocProvider.value(
value: cubit,
child: BlocConsumer<MyCubit, MyState>(
// key: ValueKey(cubit),
listener: (context, state) {},
builder: (context, state) {
return Text('state2 is $state (${state.hashCode})');
},
),
),
//
// Consumer in stateless widget
//
BlocProvider.value(
value: MyCubit(state),
child: MyStatelessWidget(),
),
Text('should be: ${state.hashCode}'),
// MyStatelessWidget(),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _refresh,
child: const Icon(Icons.refresh),
),
);
}
void _refresh() {
setState(() {});
}
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocConsumer<MyCubit, MyState>(
// key: UniqueKey(),
listener: (context, state) {},
builder: (context, state) {
return Text('state3 is $state (${state.hashCode})');
},
);
}
}
class MyCubit extends Cubit<MyState> {
MyCubit(super.initialState);
}
class MyState {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment