一統天下 flutter - widget Sliver: CustomScrollView/SliverPadding/SliverSafeArea - 通過 slivers 實現滾動效果

源碼 https://github.com/webabcd/flutter_demo
作者 webabcd

一統天下 flutter - widget Sliver: CustomScrollView/SliverPadding/SliverSafeArea - 通過 slivers 實現滾動效果

示例如下:

lib\widget\sliver\custom_scroll_view.dart

/*
 * CustomScrollView - 通過 slivers 實現滾動效果
 * SliverSafeArea - 爲 sliver 指定安全區域(關於安全區域請參見 /lib/ui/safe_area.dart)
 * SliverPadding - 爲指定的 sliver 設置邊距
 *
 * 關於 Scrollbar, ScrollController, ScrollNotification 請參見 /lib/widget/scroll/ 中的示例的相關說明
 */

import 'dart:math';

import 'package:flutter/material.dart';

class CustomScrollViewDemo extends StatefulWidget {
  const CustomScrollViewDemo({Key? key}) : super(key: key);

  @override
  _CustomScrollViewDemoState createState() => _CustomScrollViewDemoState();
}

class _CustomScrollViewDemoState extends State<CustomScrollViewDemo> {

  final _random = Random();
  Color _getRandomColor() {
    return Color.fromARGB(255, _random.nextInt(256), _random.nextInt(256), _random.nextInt(256),);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      /// CustomScrollView 用於通過其 slivers 實現滾動效果
      body: CustomScrollView(
        /// 滾動方向(vertical 或 horizontal)
        /// 如果需要兩個方向都滾,那麼就需要用兩個 CustomScrollView
        scrollDirection: Axis.vertical,
        /// 留白區域佔可視區的百分比(0.0 - 1.0 之間)
        anchor: 0.0,
        /// 滾動的響應方式
        ///   NeverScrollableScrollPhysics() - 禁止滾動
        ///   BouncingScrollPhysics() - 允許滾動,滾到邊緣後會有類似 ios 的彈簧效果
        ///   ClampingScrollPhysics() - 允許滾動,滾到邊緣後會有類似 android 的光波效果
        ///   AlwaysScrollableScrollPhysics() - 允許滾動,滾到邊緣後在 ios 中會有彈簧效果,在 android 中會有光波效果
        ///   RangeMaintainingScrollPhysics() - 有 AlwaysScrollableScrollPhysics() 的效果,並且在滾動中即使內容出現了增多或減少也不會影響滾動
        physics: const RangeMaintainingScrollPhysics(),
        /// 是否反向
        reverse: false,
        /// 通過 slivers 實現滾動效果
        slivers: [
          /// SliverSafeArea - 爲 sliver 指定安全區域
          SliverSafeArea(
            sliver: SliverList(
              delegate: SliverChildBuilderDelegate((context, index) =>
                  Container(color: _getRandomColor(), height: 150,),
                childCount: 5,
              ),
            ),
          ),

          /// SliverPadding - 爲指定的 sliver 設置邊距
          SliverPadding(
            padding: const EdgeInsets.all(50),
            sliver: SliverList(
              delegate: SliverChildBuilderDelegate((context, index) =>
                  Container(color: _getRandomColor(), height: 150,),
                childCount: 5,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

源碼 https://github.com/webabcd/flutter_demo
作者 webabcd

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章