Untitled
unknown
plain_text
2 years ago
2.4 kB
2
Indexable
Never
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter/material.dart'; void main() { runApp(const TestApp()); } class TestApp extends StatelessWidget { const TestApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: BlocProvider( create: (_) => TestBloc(), child: const MyWidget(), ), ); } } class MyWidget extends StatefulWidget { const MyWidget({Key? key}) : super(key: key); @override State<MyWidget> createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { @override void initState() { // context.read<TestBloc>().functionA(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( body: BlocListener<TestBloc, int>( listenWhen: ((previous, current) => current < previous), listener: (ctx, state) { final snackBar = SnackBar(content: Text('$state')); ScaffoldMessenger.of(context).showSnackBar(snackBar); }, child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ Container( alignment: Alignment.center, child: GestureDetector( onTap: () { context.read<TestBloc>().functionA(); }, child: Container( padding: const EdgeInsets.all(8), color: Colors.blue, child: const Text('Click Function A'), ), ), ), const SizedBox(height: 8), Container( alignment: Alignment.center, child: GestureDetector( onTap: () { context.read<TestBloc>().functionB(); }, child: Container( padding: const EdgeInsets.all(8), color: Colors.blue, child: const Text('Click Function B'), ), ), ) ], ), ), ), ); } } class TestBloc extends Cubit<int> { TestBloc() : super(0); void functionA() { print("Hello Function A"); emit(state * 2); } void functionB() { print("Hello Function B"); emit(state - 10); } }