Created
October 3, 2022 09:37
-
-
Save 000407/6ca2e336f330c15480e38caffe4c83c6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class DiceFaceCubit extends Cubit<int?> { | |
| DiceFaceCubit(): super(null); | |
| void rollDice() { | |
| emit(Random().nextInt(6) + 1); | |
| } | |
| } | |
| class MyApp extends StatelessWidget { | |
| const MyApp({Key? key}): super(key: key); | |
| @override | |
| Widget build(BuildContext context) { | |
| return BlockProvider( // BlocProvider works as a dependency injector | |
| create: (_) => DiceFaceCubit(), // creates the cubit and makes it accessible | |
| child: MaterialApp( | |
| title: 'Title', | |
| theme: ThemeData( | |
| primarySwatch: Colors.blue | |
| ), | |
| home: const MyHomePage() | |
| ), | |
| ); | |
| } | |
| } | |
| // Either (if it's a larger widget that only a certain portion of it depends on the state provided by the cubit) | |
| class MyHomePage extends StatelessWidget { | |
| const MyHomePage({Key? key}): super(key: key); | |
| @override | |
| Widget build(BuildContext context) { | |
| return Scaffold( | |
| body: Center( | |
| child: GestureDetector( | |
| onTap: () { | |
| context.read<DiceFaceCubit>().rollDice() | |
| }, | |
| child: Container( | |
| height: 100, | |
| width: 100, | |
| decoration: BoxDecotation( | |
| borderRadius: BorderRadius.circular(5), | |
| color: Colors.blue | |
| ), | |
| child: BlocBuilder<DiceFaceCubit, int?>( | |
| builder: (context, state) { | |
| return Text(state != null ? "$state": "click"); | |
| } | |
| ) | |
| ) | |
| ) | |
| ) | |
| ); | |
| } | |
| } | |
| // Or (if there's a standalone widget that depend entirely on the state provided by the cubit) | |
| class MyHomePage extends StatelessWidget { | |
| const MyHomePage({Key? key}): super(key: key); | |
| @override | |
| Widget build(BuildContext context) { | |
| final state = context.watch<DiceFaceCubit>().state; | |
| return Scaffold( | |
| body: Center( | |
| child: GestureDetector( | |
| onTap: () { | |
| context.read<DiceFaceCubit>().rollDice() | |
| }, | |
| child: Container( | |
| height: 100, | |
| width: 100, | |
| decoration: BoxDecotation( | |
| borderRadius: BorderRadius.circular(5), | |
| color: Colors.blue | |
| ), | |
| child: Text(state != null ? "$state": "click") | |
| ) | |
| ) | |
| ) | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment