Flutter 學習之旅(四十九) Flutter 狀態(tài) flutter_bloc學習(三)

利用flutter_bloc 完成listview 中checkbox 的勾選,我在寫的過程中發(fā)現(xiàn)這個里面的坑還是有很多的,先上一下效果圖


GIF 2020-11-2 14-59-32.gif

在寫這個demo 的過程中我一共找到了自己好幾處運用flutter_bloc的錯誤之處的地方,
第一個問題,

  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

這個問題就是利用BlocProvider.of<C>(this)的方法時找不到這個provider ,這其中的原因有2個,其中一個是在child 的context 并沒有provider 的依賴,

BlocProvider(
                create: (_) => TsmListCheckItem.forInstance(map),
                child:_TsmItemWidget(list[index], index,map),
              );
            }

即在上面中的child 直接使用BlocBuilder,并沒有使用StatelessWidget 來包裹,
第二個問題就是我所遇到的,在使用BlocBuilder 中,沒有指定 cubit 的類型,

///錯誤寫法
BlocBuilder(
                builder: (con, state) {
                  return Checkbox(
                    value: state[index],
                    activeColor: Colors.redAccent,
                    /// 勾選后顏色
                    onChanged: (isSelect) {
                      context.bloc<TsmListCheckItem>().add(index);
                    },
                  );
                },
              )

上面就是我的錯誤寫法, 正確寫法在這里應該指定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,第二個問題就非常有意思了, 那就是我利用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 = ['測試1', '測試2', '測試3', '測試4', '測試5', '測試6', '測試7', '測試8', '測試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> 來保存每個位置的狀態(tài),每一個item 提供一個provider , 在每次勾選的時候改變這個map 的index 的bool類型的值,我在寫的過程中發(fā)現(xiàn) BlocProvider 中的 create 的 TsmListCheckItem.forInstance(map) 這個方法會調用多次,也就是說如果外部這個map的類型不跟著勾選后的結果變更的話,就會導致在調用 BlocProvider 中的 create 的方法的時候,讓狀態(tài)變成最開始的默認值,所以這里我增加了一層BlocListener ,在每次勾選后改變外部這個map的值,這樣可以在后續(xù)調用TsmListCheckItem.forInstance(map) 的方法的時候,狀態(tài)也是改變后的狀態(tài),這個問題我查了好久, 相信如果大家好好體會的話還是非常有幫助的,

其實這個問題是我強行給自己制造的,如果我用BlocProvider 包裹的是LsitView,而不是LsitView 的Item ,那么上面那種重復創(chuàng)建的問題就不會存在了,最開始的寫法也是這么寫的,這里這是為了把問題展示出來才修改到Iitem 上的,

最后一個問題,就是在mapEventToState 的時候不能對這個state修改,而是必須要重新new ,原因就是在接下來會遇到 state==nextState 這個判斷,如果對state做修改的話,這個判斷就會一直相等,從而無法生成新的狀態(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 = ['測試1', '測試2', '測試3', '測試4', '測試5', '測試6', '測試7', '測試8', '測試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,
              ),
            ],
          )
        ],
      ),
    );
  }
}

我學習flutter的整個過程都記錄在里面了
http://www.lxweimin.com/c/36554cb4c804

最后附上demo 地址

https://github.com/tsm19911014/tsm_flutter

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,461評論 6 532
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,538評論 3 417
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,423評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,991評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,761評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,207評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,268評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,419評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 48,959評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,653評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,901評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,678評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,978評論 2 374