與Provider概念相似
將CounterCubit 透過 BlocProvider提供給 畫面
本次實作有三個檔案
CounterCubit
變化// Cubit<int> 是計數器用的事件監聽
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0); //super(0) 代表初始值設為0
//透過以下兩中方法增加減少state數值
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Counter Bloc'),
),
//將CounterCubit計數器實體 , 使用在child widget
body: BlocBuilder<CounterCubit, int>(
builder: (context, state) => Center(
child: Text(
state.toString(),
),
),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
child: const Icon(Icons.add),
//點擊增加按鈕呼叫 CounterCubitu increment方法
onPressed: () => context.read<CounterCubit>().increment(),
),
const SizedBox(height: 4),
FloatingActionButton(
child: const Icon(Icons.remove),
//呼叫 CounterCubitu decrement方法
onPressed: () => context.read<CounterCubit>().decrement(),
),
],
),
);
}
child: MaterialApp(
title: 'Flutter Demo',
initialRoute: '/',
routes: {
'/': (context) => const MainView(),
BASIC: (context) => const BasicView(),
IMAGEPICKER: (context) => const ImagePickerPage(),
CALLBACK: (context) => const CallBackView(),
SHOP: (context) => ChangeNotifierProvider(
create: (context) => Counter(),
child: const ShopView(),
),
//Shopping Provider View
LOGIN: (context) => const Login(),
CATALOG: (context) => const Catalog(),
CART: (context) => const Cart(),
//增加Route BlocProvider 提供 CounterCubit 給 CounterPage
COUNTER: (context) => BlocProvider(
create: (context) => CounterCubit(),
child: const CounterPage(),
),
},
theme: ThemeData(
primarySwatch: Colors.blueGrey,
),
),