Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.6 kB
3
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>(
        listener: (ctx, state) {
          final snackBar = SnackBar(content: Text('$state'));
          ScaffoldMessenger.of(context).showSnackBar(snackBar);
        },
        child: 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 me'),
            ),
          ),
        ),
      ),
    );
  }
}

class TestBloc extends Cubit<int> {
  TestBloc() : super(0);

  void functionA() {
    print("Hello Cubit");
    emit(state + 1);
  }
}