Flutter基礎-027-CustomScrollView

天色將變發表於2021-03-01
解決的問題

當一個頁面中,既有GridView 又有ListView,不能進行統一滑動時,二者有各自的滑動區域。CustomScrollView可以將二者結合起來,一起滑動。

CustomScrollView關鍵屬性
  • slivers: [],將Silver化的GridView與ListView扔到裡面即可。
SliverGrid,Silver化的GridView

const SliverGrid({ Key key, @required SliverChildDelegate delegate,// 構建每個item的widget @required this.gridDelegate,//計算每行/列的個數演算法 })

SliverFixedExtentList,Sliver化的ListView

SliverFixedExtentList({ Key key, @required SliverChildDelegate delegate, //構建每個item的widget @required this.itemExtent,//指定行高 }) image.png

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: CustomScrollView(
        slivers: <Widget>[
          SliverPadding(
            padding: const EdgeInsets.all(8.0),
            sliver: new SliverGrid(
              //Grid
              gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3, //Grid按兩列顯示
                mainAxisSpacing: 10.0,
                crossAxisSpacing: 10.0,
                childAspectRatio: 4.0,
              ),
              delegate: new SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  //建立子widget
                  return new Container(
                    alignment: Alignment.center,
                    color: Colors.orange[100 * (index % 9)],
                    child: new Text('grid item $index'),
                  );
                },
                childCount: 10,
              ),
            ),
          ),
          //List
          new SliverFixedExtentList(
            itemExtent: 50.0,
            delegate: new SliverChildBuilderDelegate(
                (BuildContext context, int index) {
              //建立列表項
              return new Container(
                alignment: Alignment.center,
                color: Colors.green[100 * (index % 9)],
                child: new Text('list item $index'),
              );
            }, childCount: 5 //10個列表項
                ),
          ),
          new SliverGrid(
            //Grid
            gridDelegate: new SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: 113, //Grid按兩列顯示
              mainAxisSpacing: 10.0,
              crossAxisSpacing: 10.0,
              childAspectRatio: 4.0,
            ),
            delegate: new SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                //建立子widget
                return new Container(
                  alignment: Alignment.center,
                  color: Colors.yellow[100 * (index % 9)],
                  child: new Text('grid item $index'),
                );
              },
              childCount: 20,
            ),
          ),
        ],
      ),
    );
  }
}

複製程式碼

相關文章