Bloc8
Bloclistener¶
Code¶
class CounterPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counterBloc = context.watch<CounterBloc>();
return BlocListener<CounterBloc, int>(
listener: (context, state) {
// 在這裡響應狀態變化
if (state == 0) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Counter is zero')),
);
}
},
child: Scaffold(
appBar: AppBar(
title: Text('Counter App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Counter Value:',
style: TextStyle(fontSize: 24),
),
Text(
'${counterBloc.state}',
style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
),
BlocBuilder<CounterBloc, int>(
builder: (context, state) {
return Text(
'$state',
style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
);
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
context.read<CounterBloc>().add(2);
},
child: Text('Increment'),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: () {
context.read<CounterBloc>().add(-1);
},
child: Text('Decrement'),
),
],
),
),
),
);
}
}
BlocListener 是一種 Flutter 小部件,它可以用來監聽 Bloc 的狀態變化並響應一次性事件,例如導航或顯示 SnackBar。
在你的程式碼中,BlocListener 被用來監聽 CounterBloc 的狀態變化。當 CounterBloc 的狀態變化時,listener 函數會被調用,並將新的狀態作為參數。
在 listener 函數中,你可以根據新的狀態來響應一次性事件。在你的程式碼中,當計數器的值為零時,會顯示一個 SnackBar。
使用 BlocListener 的基本步驟如下:
- 創建一個
BlocListener小部件,並指定要監聽的 Bloc 類型和狀態類型。 - 提供一個
listener函數,該函數會在 Bloc 的狀態變化時被調用。listener函數接收兩個參數:context和state。context是當前的BuildContext,state是 Bloc 的新狀態。 - 在
listener函數中,根據新的狀態來響應一次性事件。 - 提供一個
child小部件,該小部件是BlocListener的子小部件。child小部件不會在 Bloc 的狀態變化時被重建。
若想使用更多listener¶
class CounterPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counterBloc = context.watch<CounterBloc>();
return MultiBlocListener(
listeners: [
BlocListener<CounterBloc, int>(
listener: (context, state) {
// 在這裡響應 CounterBloc 的狀態變化
if (state == 0) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Counter is zero')),
);
}
},
),
// 你可以在這裡添加更多的 BlocListener
],
child: Scaffold(
appBar: AppBar(
title: Text('Counter App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Counter Value:',
style: TextStyle(fontSize: 24),
),
Text(
'${counterBloc.state}',
style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
),
BlocBuilder<CounterBloc, int>(
builder: (context, state) {
return Text(
'$state',
style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
);
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
context.read<CounterBloc>().add(2);
},
child: Text('Increment'),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: () {
context.read<CounterBloc>().add(-1);
},
child: Text('Decrement'),
),
],
),
),
),
);
}
}
Last update :
13 novembre 2024
Created : 13 novembre 2024
Created : 13 novembre 2024