利用flutter_bloc 完成listview 中checkbox 的勾選,我在寫的過程中發(fā)現(xiàn)這個(gè)里面的坑還是有很多的,先上一下效果圖
在寫這個(gè)demo 的過程中我一共找到了自己好幾處運(yùn)用flutter_bloc的錯(cuò)誤之處的地方,
第一個(gè)問題,
BlocProvider.of() called with a context that does not contain a Cubit of type $T.
No ancestor could be found starting from the context that was passed to BlocProvider.of<$T>().
This can happen if the context you used comes from a widget above the BlocProvider.
The context used was: $context
這個(gè)問題就是利用BlocProvider.of<C>(this)的方法時(shí)找不到這個(gè)provider ,這其中的原因有2個(gè),其中一個(gè)是在child 的context 并沒有provider 的依賴,
BlocProvider(
create: (_) => TsmListCheckItem.forInstance(map),
child:_TsmItemWidget(list[index], index,map),
);
}
即在上面中的child 直接使用BlocBuilder,并沒有使用StatelessWidget 來包裹,
第二個(gè)問題就是我所遇到的,在使用BlocBuilder 中,沒有指定 cubit 的類型,
///錯(cuò)誤寫法
BlocBuilder(
builder: (con, state) {
return Checkbox(
value: state[index],
activeColor: Colors.redAccent,
/// 勾選后顏色
onChanged: (isSelect) {
context.bloc<TsmListCheckItem>().add(index);
},
);
},
)
上面就是我的錯(cuò)誤寫法, 正確寫法在這里應(yīng)該指定provider的類型,否則provider.of 是肯定找不到類型的,
///正確的寫法
BlocBuilder<TsmListCheckItem, Map<int, bool>>(///給blocBuilder 指定類型,
builder: (con, state) {
return Checkbox(
value: state[index],
activeColor: Colors.redAccent,
/// 勾選后顏色
onChanged: (isSelect) {
context.bloc<TsmListCheckItem>().add(index);
},
);
},
)
2,第二個(gè)問題就非常有意思了, 那就是我利用BlocProvider 包裹listview 的item,每次更改后的狀態(tài)在滑出屏幕再滑回后又變成初始化的狀態(tài)了,下面我上一下我修改過后的代碼
class _TsmListViewCheckState extends State<TsmListViewCheckPage> {
ScrollController _controller;
List<String> list;
Map<int,bool> map;
@override
void initState() {
_controller = ScrollController();
list = ['測(cè)試1', '測(cè)試2', '測(cè)試3', '測(cè)試4', '測(cè)試5', '測(cè)試6', '測(cè)試7', '測(cè)試8', '測(cè)試9'];
map=HashMap();
for(int i=0;i<list.length;i++){
map.putIfAbsent(i, () => false);
}
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ListView 勾選'),
centerTitle: true,
),
body:ListView.builder(
itemCount: list.length,
physics: BouncingScrollPhysics(),
controller: _controller,
itemBuilder: (con, index) {
return BlocProvider(
create: (_) => TsmListCheckItem.forInstance(map),
child:_TsmItemWidget(list[index], index,map),
);
})
);
}
}
class _TsmItemWidget extends StatelessWidget {
final String _tag;
final Map<int,bool> _map;
final int index;
_TsmItemWidget(this._tag, this.index,this._map);
@override
Widget build(BuildContext context) {
return BlocListener<TsmListCheckItem, Map<int, bool>>(
listener: (con,state){
_map[index]=!_map[index];
},
child: Column(
children: [
....
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
...
BlocBuilder<TsmListCheckItem, Map<int, bool>>(
builder: (con, state) {
return Checkbox(
value: state[index],
activeColor: Colors.redAccent,
/// 勾選后顏色
onChanged: (isSelect) {
context.bloc<TsmListCheckItem>().add(index);
},
);
},
),
....
],
)
],
),
);
}
}
這里我隱藏了部分代碼,我的思路就是利用map<int,bool> 來保存每個(gè)位置的狀態(tài),每一個(gè)item 提供一個(gè)provider , 在每次勾選的時(shí)候改變這個(gè)map 的index 的bool類型的值,我在寫的過程中發(fā)現(xiàn) BlocProvider 中的 create 的 TsmListCheckItem.forInstance(map) 這個(gè)方法會(huì)調(diào)用多次,也就是說如果外部這個(gè)map的類型不跟著勾選后的結(jié)果變更的話,就會(huì)導(dǎo)致在調(diào)用 BlocProvider 中的 create 的方法的時(shí)候,讓狀態(tài)變成最開始的默認(rèn)值,所以這里我增加了一層BlocListener ,在每次勾選后改變外部這個(gè)map的值,這樣可以在后續(xù)調(diào)用TsmListCheckItem.forInstance(map) 的方法的時(shí)候,狀態(tài)也是改變后的狀態(tài),這個(gè)問題我查了好久, 相信如果大家好好體會(huì)的話還是非常有幫助的,
其實(shí)這個(gè)問題是我強(qiáng)行給自己制造的,如果我用BlocProvider 包裹的是LsitView,而不是LsitView 的Item ,那么上面那種重復(fù)創(chuàng)建的問題就不會(huì)存在了,最開始的寫法也是這么寫的,這里這是為了把問題展示出來才修改到Iitem 上的,
最后一個(gè)問題,就是在mapEventToState 的時(shí)候不能對(duì)這個(gè)state修改,而是必須要重新new ,原因就是在接下來會(huì)遇到 state==nextState 這個(gè)判斷,如果對(duì)state做修改的話,這個(gè)判斷就會(huì)一直相等,從而無法生成新的狀態(tài)
class TsmListCheckItem extends Bloc<int,Map<int,bool>>{
TsmListCheckItem(Map<int,bool> initialState) : super(initialState);
@override
Stream<Map<int,bool>> mapEventToState(int index) async*{
HashMap<int ,bool> nextState=Map.from(state);
nextState[index]=!state[index];
yield nextState;
}
static TsmListCheckItem forInstance(Map<int,bool> map) {
TsmListCheckItem item=TsmListCheckItem(map);
return item;
}
}
下面我貼一下源碼,
class TsmListCheckItem extends Bloc<int,Map<int,bool>>{
TsmListCheckItem(Map<int,bool> initialState) : super(initialState);
@override
Stream<Transition<int, Map<int, bool>>> transformTransitions(Stream<Transition<int, Map<int, bool>>> transitions) {
return super.transformTransitions(transitions);
}
@override
Stream<Map<int,bool>> mapEventToState(int index) async*{
HashMap<int ,bool> nextState=Map.from(state);
nextState[index]=!state[index];
yield nextState;
}
static TsmListCheckItem forInstance(Map<int,bool> map) {
TsmListCheckItem item=TsmListCheckItem(map);
return item;
}
}
class TsmListViewCheckPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => _TsmListViewCheckState();
}
class _TsmListViewCheckState extends State<TsmListViewCheckPage> {
ScrollController _controller;
List<String> list;
Map<int,bool> map;
@override
void initState() {
_controller = ScrollController();
list = ['測(cè)試1', '測(cè)試2', '測(cè)試3', '測(cè)試4', '測(cè)試5', '測(cè)試6', '測(cè)試7', '測(cè)試8', '測(cè)試9'];
map=HashMap();
for(int i=0;i<list.length;i++){
map.putIfAbsent(i, () => false);
}
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ListView 勾選'),
centerTitle: true,
),
body:ListView.builder(
itemCount: list.length,
physics: BouncingScrollPhysics(),
controller: _controller,
itemBuilder: (con, index) {
return BlocProvider(
create: (_) => TsmListCheckItem.forInstance(map),
child:_TsmItemWidget(list[index], index,map),
);
})
);
}
}
class _TsmItemWidget extends StatelessWidget {
final String _tag;
final Map<int,bool> _map;
final int index;
_TsmItemWidget(this._tag, this.index,this._map);
@override
Widget build(BuildContext context) {
return BlocListener<TsmListCheckItem, Map<int, bool>>(
listener: (con,state){
_map[index]=!_map[index];
},
child: Column(
children: [
Stack(
children: [
Positioned(
child: Container(
padding: const EdgeInsets.fromLTRB(22, 10, 22, 10),
child: ClipRRect(
child: Image(
image: AssetImage('images/hor.jpg'),
width: double.infinity,
fit: BoxFit.fitWidth,
),
borderRadius: BorderRadius.all(Radius.circular(6)),
),
),
),
Positioned(
top: 10,
left: 22,
child: Container(
padding: const EdgeInsets.fromLTRB(5, 3, 5, 3),
decoration: BoxDecoration(
color: Colors.redAccent,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(6),
bottomRight: Radius.circular(6))),
child: Text(_tag),
),
)
],
),
SizedBox(
height: 10,
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: 20,
),
Expanded(
flex: 1,
child: Text(_tag * 12),
),
SizedBox(
width: 10,
),
Text(index.toString()),
BlocBuilder<TsmListCheckItem, Map<int, bool>>(
builder: (con, state) {
return Checkbox(
value: state[index],
activeColor: Colors.redAccent,
/// 勾選后顏色
onChanged: (isSelect) {
context.bloc<TsmListCheckItem>().add(index);
},
);
},
),
SizedBox(
width: 20,
),
],
)
],
),
);
}
}
我學(xué)習(xí)flutter的整個(gè)過程都記錄在里面了
http://www.reibang.com/c/36554cb4c804
最后附上demo 地址