今天要教大家使用Bloc的BlocConsumer,讓狀態改變,但我們沒有想要更新畫面的時候,就可以用Listener去執行特定的事情或是顯示出彈跳視窗,我會繼續將連兩天的Flutter Package - Bloc(一)及Flutter Package - Bloc(二)繼續延伸,讓大家更能夠了解Bloc的應用
修改bloc_screen.dart檔案
將BlocProvider改為BlocConsumer,並在裡面加入listener監聽State
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'counter_management_bloc.dart';
class BlocScreen extends StatelessWidget {
const BlocScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: BlocProvider(
create: (_) => CounterManagementBloc(),
child: BlocConsumer<CounterManagementBloc, CounterManagementState>(listener: (context, state) async {
if (state is CounterManagementDecreasedFailure) {
await showDialog<String>(
context: context,
builder: (BuildContext context) {
return AlertDialog(content: Text(state.reason));
},
);
}
if (state is CounterManagementIncreasedFailure) {
await showDialog<String>(
context: context,
builder: (BuildContext context) {
return AlertDialog(content: Text(state.reason));
},
);
}
}, builder: (context, state) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: () {
context.read<CounterManagementBloc>().add(CounterManagementDecreased());
},
child: const Icon(Icons.remove),
),
Text(state.count.toString()),
ElevatedButton(
onPressed: () {
context.read<CounterManagementBloc>().add(CounterManagementIncreased());
},
child: const Icon(Icons.add),
),
],
),
const SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () {
context.read<CounterManagementBloc>().add(CounterManagementReset());
},
child: const Text("reset"),
),
const SizedBox(
height: 100,
),
],
),
);
}),
));
}
}