Flutter ListView和GridView嵌套

2021-04-25 14:33:54 浏览数 (1)

Screenshot_1619146087.png

要实现如图的效果

总体结构

整体结构是一个ListView,LiseView里面嵌套一个Container(热门歌单) ListView(顶部3个横着的Item)GridView(九宫格Item)

核心代码
代码语言:javascript复制
Widget _bodyWidget(HotSongSheetsState state, Dispatch dispatch,ViewService viewService) {
  return  WillPopScope(
    child: Scaffold(
      backgroundColor: Global.pageBackgroundColor,
      appBar: AppBarWidget('', viewService.context),
      body: ListView(
        children: [
          Container(
            height: ScreenAdaper.width2px(40),
            alignment: Alignment.topLeft,
            margin: EdgeInsets.only(left: 16),
            child: BaseText.baseText('热门歌单', 24, '111E36'),
          ),
          Container(
            height: ScreenAdaper.width2px(15),
          ),
          Container(
           child:  _songSheetListWidget(state,dispatch),
         ),
        ],
      ),
    ),
  );

}
代码语言:javascript复制
Widget _songSheetListWidget(HotSongSheetsState state, Dispatch dispatch){
  if(state.hotSongSheetList.list.length <= 3){
    return _getListView(state,dispatch);
  }else{
    return Column(
      children: [
        _getListView(state,dispatch),
        _gridView(state,dispatch),
      ],
    );
  }
}
ListView
代码语言:javascript复制
Widget _getListView(HotSongSheetsState state, Dispatch dispatch){
  return ListView.builder(
    shrinkWrap: true, //解决无线高度问题
    physics: new NeverScrollableScrollPhysics(), //禁用滑动事件
    itemBuilder: (context, index) {
      return HotSongSheetListItem(
        data: state.hotSongSheetList.list[index],
        dispatch: dispatch,
      );
    },
    itemCount: state.hotSongSheetList.list.length > 3?3:state.hotSongSheetList.list.length,
  );
}
GridView
代码语言:javascript复制
Widget _gridView(HotSongSheetsState state, Dispatch dispatch) {
  return GridView.builder(
      shrinkWrap: true,
      //解决无线高度问题
      physics: new NeverScrollableScrollPhysics(),
      //禁用滑动事件
      scrollDirection: Axis.vertical,
      // 水平滚动
      controller: state.scrollController,
      padding: EdgeInsets.only(left: 16.0, top: 0, right: 16),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3, //每行显示3列
        childAspectRatio: 110 / 150, //显示区域宽高相等
        mainAxisSpacing: 6.0, //每行的间距
        crossAxisSpacing: 6.0, //每列的间距
      ),
      itemCount: state.hotSongSheetList.list.length,
      itemBuilder: (context, index) {
        return HotSongSheetItem(
          dispatch: dispatch,
          data: state.hotSongSheetList.list[index],
        );
      });
}

其他部分代码就不粘贴出来了。代码很简单一看都明白

0 人点赞