Flutter 使用GridView寫一個根據child數量自動增加的GridList

MrDotY發表於2021-03-04
class GrideMenu extends StatelessWidget {
GrideMenu({
	Key key,
    @required this.items,
    @required this.onTap,
    @required this.crossAxisCount 
   }):super(key:key);
   
	final List items;  //children的數量
	final Function onTap; //child的點選事件
	final int crossAxisCount; //每行的child個數
    
  Widget build(context) {
  	
    //對children的數量取餘
    //如果不等於0就說明存在多出來的children
    //那麼行數就必須加1
    final int more = items.length % crossAxisCount;
    final int minCount = items.length ~/ crossAxisCount;
    final int maxCount = more == 0 ? minCount : minCount + 1;
    //獲取寬度
    final screenWidth = MediaQuery.of(context).size.width;
    //求取單個child的寬度
    final itemWidth = screenWidth /crossAxisCount;
    return Container(
      width: context.width,
      padding: EdgeInsets.all(8),
      height: maxCount * (itemWidth - 10.0),
      child: GridView.builder(
      	//不允許GridView內的children滾動
          physics: NeverScrollableScrollPhysics(),
          itemCount: items.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              //橫軸元素個數
              crossAxisCount: crossAxisCount,
              //縱軸間距
              mainAxisSpacing: 5.0,
              //橫軸間距
              crossAxisSpacing: 5.0,
              //子元件寬高長度比例
              childAspectRatio: 1),
          itemBuilder: (ctx, index) {
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: onTap,
                  child: Container(
                    color:Color(0xff0099ff)
                  ),
                ),
              ],
            );
          }),
    );
  }
}

複製程式碼

相關文章