Creating Bloc Provider for ProductsCubit

Inside the product_screen.dart file we created earlier put the following code:

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:techamp_flutter_shopping_app/app.dart';

class ProductsScreen extends StatelessWidget {
  const ProductsScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => getIt<ProductsCubit>()..getAll(),
      child: Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: const Icon(Icons.person, color: Colors.white),
            onPressed: () => context.navigator.push(Routes.profileScreen),
          ),
        ),
        floatingActionButton: const _CartButton(),
        body: Container(),
      ),
    );
  }
}

The _CartButton is a stateless widget placed inside product_screen.dart that builds a clickable widget we will use to navigate to the cartScreen

class _CartButton extends StatelessWidget {
  const _CartButton({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CartCubit, CartState>(
      builder: (_, state) {
        final count = state.carts.totalProductsQuantity;
        return Stack(
          overflow: Overflow.visible,
          children: [
            FloatingActionButton(
              onPressed: () => context.navigator.push(Routes.cartScreen),
              child: const Icon(Icons.shopping_cart),
            ),
            if (count > 0)
              Positioned(
                top: -4,
                right: -2,
                child: CircleAvatar(
                  radius: 12,
                  backgroundColor: Colors.white,
                  child: Text('$count'),
                ),
              )
          ],
        );
      },
    );
  }
}

Last updated