Flutter初探--半自定義ExpansionTile

背景

做移動(dòng)端開發(fā)的朋友經(jīng)常會(huì)遇到數(shù)據(jù)需要層級(jí)展示的場(chǎng)景搀捷,如二級(jí)或者三級(jí)列表狈邑。因此flutter也為我們提供了列表中可用來折疊的組件ExpansionTile巧婶,基本能滿足我們的需求,但是...這玩意可自定義程度真的有限!??用 ExpansionTile實(shí)現(xiàn)效果如下圖所示:

未展開的效果圖

展開的效果圖

存在問題:
1.ExpansionTile背景色展開后才顯示
2.上下分割線展開后才顯示
3.分割線顏色不可修改
4.標(biāo)題和圖標(biāo)展開時(shí)展示成了主題色

那如何解決這些問題呢维蒙? 先看源碼再說~

源碼解析

const ExpansionTile({
    Key key,
    this.leading,
    @required this.title,
    this.backgroundColor,
    this.onExpansionChanged,
    this.children = const <Widget>[],
    this.trailing,
    this.initiallyExpanded = false,
  }) : assert(initiallyExpanded != null),
       super(key: key);

leading:左側(cè)頭部組件,如用戶頭像
title:常見標(biāo)題組件
backgroundColor:展開時(shí)子列表背景色
children:展開的widgets
trailing:用于替換尾部箭頭的組件
initiallyExpanded:設(shè)置默認(rèn)是否展開

可以看到,ExpansionTile提供的屬性非常有限妓雾,并沒有提供我們用于解決上邊問題的方法,ExpansionTile中的代碼并不多垒迂,其中定義了各種動(dòng)畫械姻,并設(shè)置了動(dòng)畫區(qū)間,ExpansionTile的展示效果也都依賴于這些顏色~

  final ColorTween _borderColorTween = ColorTween();
  final ColorTween _headerColorTween = ColorTween();
  final ColorTween _iconColorTween = ColorTween();
  final ColorTween _backgroundColorTween = ColorTween();

  AnimationController _controller;
  Animation<double> _iconTurns;
  Animation<double> _heightFactor;
  Animation<Color> _borderColor;
  Animation<Color> _headerColor;
  Animation<Color> _iconColor;
  Animation<Color> _backgroundColor;

_ExpansionTileState中定義的各種動(dòng)畫

@override
  void didChangeDependencies() {
    final ThemeData theme = Theme.of(context);
    _borderColorTween
      ..end = theme.dividerColor;
    _headerColorTween
      ..begin = theme.textTheme.subhead.color
      ..end = theme.accentColor;
    _iconColorTween
      ..begin = theme.unselectedWidgetColor
      ..end = theme.accentColor;
    _backgroundColorTween
      ..end = widget.backgroundColor;
    super.didChangeDependencies();
  }

復(fù)寫didChangeDependencies來設(shè)置顏色區(qū)間机断,所以看到這里楷拳,我們需要做的只是拷貝一份出來,修改這里的顏色區(qū)間邏輯而已~

完整代碼

import 'package:flutter/material.dart';

// import 'colors.dart';
// import 'icons.dart';
// import 'list_tile.dart';
// import 'theme.dart';
// import 'theme_data.dart';

const Duration _kExpand = Duration(milliseconds: 200);

/// A single-line [ListTile] with a trailing button that expands or collapses
/// the tile to reveal or hide the [children].
///
/// This widget is typically used with [ListView] to create an
/// "expand / collapse" list entry. When used with scrolling widgets like
/// [ListView], a unique [PageStorageKey] must be specified to enable the
/// [HJExpansionTile] to save and restore its expanded state when it is scrolled
/// in and out of view.
///
/// See also:
///
///  * [ListTile], useful for creating expansion tile [children] when the
///    expansion tile represents a sublist.
///  * The "Expand/collapse" section of
///    <https://material.io/guidelines/components/lists-controls.html>.

// 分割線顯示時(shí)機(jī)
enum DividerDisplayTime {
  always, //總是顯示
  opened, //展開時(shí)顯示
  closed, //關(guān)閉時(shí)顯示
  never //不顯示
}

class HJExpansionTile extends StatefulWidget {
  /// Creates a single-line [ListTile] with a trailing button that expands or collapses
  /// the tile to reveal or hide the [children]. The [initiallyExpanded] property must
  /// be non-null.
  const HJExpansionTile({
    Key key,
    this.leading,
    @required this.title,
    this.backgroundColor,
    this.dividerColor,
    this.iconColor,
    this.dividerDisplayTime,
    this.onExpansionChanged,
    this.children = const <Widget>[],
    this.trailing,
    this.initiallyExpanded = false,
  })  : assert(initiallyExpanded != null),
        super(key: key);

  /// A widget to display before the title.
  ///
  /// Typically a [CircleAvatar] widget.
  final Widget leading;

  /// The primary content of the list item.
  ///
  /// Typically a [Text] widget.
  final Widget title;

  /// Called when the tile expands or collapses.
  ///
  /// When the tile starts expanding, this function is called with the value
  /// true. When the tile starts collapsing, this function is called with
  /// the value false.
  final ValueChanged<bool> onExpansionChanged;

  /// The widgets that are displayed when the tile expands.
  ///
  /// Typically [ListTile] widgets.
  final List<Widget> children;

  /// The color to display behind the sublist when expanded.
  final Color backgroundColor;

  /// A widget to display instead of a rotating arrow icon.
  final Widget trailing;

  /// Specifies if the list tile is initially expanded (true) or collapsed (false, the default).
  final bool initiallyExpanded;

  final Color dividerColor;

  final DividerDisplayTime dividerDisplayTime;

  final Color iconColor;

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

class _HJExpansionTileState extends State<HJExpansionTile>
    with SingleTickerProviderStateMixin {
  static final Animatable<double> _easeOutTween =
      CurveTween(curve: Curves.easeOut);
  static final Animatable<double> _easeInTween =
      CurveTween(curve: Curves.easeIn);
  static final Animatable<double> _halfTween =
      Tween<double>(begin: 0.0, end: 0.5);

  final ColorTween _borderColorTween = ColorTween();
  final ColorTween _headerColorTween = ColorTween();
  final ColorTween _iconColorTween = ColorTween();
  final ColorTween _backgroundColorTween = ColorTween();

  AnimationController _controller;
  Animation<double> _iconTurns;
  Animation<double> _heightFactor;
  Animation<Color> _borderColor;
  Animation<Color> _headerColor;
  Animation<Color> _iconColor;
  Animation<Color> _backgroundColor;

  bool _isExpanded = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: _kExpand, vsync: this);
    _heightFactor = _controller.drive(_easeInTween);
    _iconTurns = _controller.drive(_halfTween.chain(_easeInTween));
    _borderColor = _controller.drive(_borderColorTween.chain(_easeOutTween));
    _headerColor = _controller.drive(_headerColorTween.chain(_easeInTween));
    _iconColor = _controller.drive(_iconColorTween.chain(_easeInTween));
    _backgroundColor =
        _controller.drive(_backgroundColorTween.chain(_easeOutTween));

    _isExpanded =
        PageStorage.of(context)?.readState(context) ?? widget.initiallyExpanded;
    if (_isExpanded) _controller.value = 1.0;
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _handleTap() {
    setState(() {
      _isExpanded = !_isExpanded;
      if (_isExpanded) {
        _controller.forward();
      } else {
        _controller.reverse().then<void>((void value) {
          if (!mounted) return;
          setState(() {
            // Rebuild without widget.children.
          });
        });
      }
      PageStorage.of(context)?.writeState(context, _isExpanded);
    });
    if (widget.onExpansionChanged != null)
      widget.onExpansionChanged(_isExpanded);
  }

  Widget _buildChildren(BuildContext context, Widget child) {
    final Color borderSideColor = _borderColor.value ?? Colors.transparent;

    return Container(
      decoration: BoxDecoration(
        color: _backgroundColor.value ?? Colors.transparent,
        border: Border(
          bottom: BorderSide(color: borderSideColor),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          ListTileTheme.merge(
            iconColor: _iconColor.value,
            textColor: _headerColor.value,
            child: ListTile(
              onTap: _handleTap,
              leading: widget.leading,
              title: widget.title,
              trailing: widget.trailing ??
                  RotationTransition(
                    turns: _iconTurns,
                    child: const Icon(Icons.expand_more),
                  ),
            ),
          ),
          ClipRect(
            child: Align(
              heightFactor: _heightFactor.value,
              child: child,
            ),
          ),
        ],
      ),
    );
  }

  @override
  void didChangeDependencies() {
    
    setupDidvierColorTween();

    setupIconColorTween();
    
    setupBackgroundColor();

    super.didChangeDependencies();
  }

  void setupDidvierColorTween() {
    final ThemeData theme = Theme.of(context);

    Color beginColor = this.widget.dividerColor ?? theme.dividerColor;
    Color endColor = beginColor;

    switch (widget.dividerDisplayTime) {
      case DividerDisplayTime.always:
        break;
      case DividerDisplayTime.opened:
        endColor = Colors.transparent;
        break;
      case DividerDisplayTime.closed:
        beginColor = Colors.transparent;
        break;
      case DividerDisplayTime.never:
        beginColor = Colors.transparent;
        endColor = Colors.transparent;
        break;
      default:
    }
    _borderColorTween
      ..begin = beginColor
      ..end = endColor;
  }

  void setupIconColorTween(){
    final ThemeData theme = Theme.of(context);

    Color beginColor = this.widget.iconColor ?? theme.unselectedWidgetColor;
    Color endColor = beginColor;

    _iconColorTween
      ..begin = beginColor
      ..end = endColor;
  }

  void setupBackgroundColor(){
    _backgroundColorTween
    ..begin = widget.backgroundColor
    ..end = widget.backgroundColor;
  }
  @override
  Widget build(BuildContext context) {
    final bool closed = !_isExpanded && _controller.isDismissed;
    return AnimatedBuilder(
      animation: _controller.view,
      builder: _buildChildren,
      child: closed ? null : Column(children: widget.children),
    );
  }
}

修改內(nèi)容說明

代碼拷出來以后吏奸,原先引入的文件會(huì)報(bào)錯(cuò)欢揖,只需將它們注釋或刪除,引入material.dart即可

import 'package:flutter/material.dart';

// import 'colors.dart';
// import 'icons.dart';
// import 'list_tile.dart';
// import 'theme.dart';
// import 'theme_data.dart';

然后擴(kuò)展了三個(gè)屬性苦丁,用來配置分割線和icon顏色浸颓,當(dāng)然icon你也可以用trail來設(shè)置~

定義了分割線枚舉來區(qū)分分割線的顯示時(shí)機(jī)

// 分割線顯示時(shí)機(jī)
enum DividerDisplayTime {
  always, //總是顯示
  opened, //展開時(shí)顯示
  closed, //關(guān)閉時(shí)顯示
  never //不顯示
}

擴(kuò)展的三個(gè)屬性

  final Color dividerColor;

  final DividerDisplayTime dividerDisplayTime;

  final Color iconColor;

調(diào)整后的初始化方法

const HJExpansionTile({
    Key key,
    this.leading,
    @required this.title,
    this.backgroundColor,
    this.dividerColor,
    this.iconColor,
    this.dividerDisplayTime,
    this.onExpansionChanged,
    this.children = const <Widget>[],
    this.trailing,
    this.initiallyExpanded = false,
  })  : assert(initiallyExpanded != null),
        super(key: key);

調(diào)整背景色,分割線顏色,icon的動(dòng)畫顏色區(qū)間

@override
  void didChangeDependencies() {
    
    setupDidvierColorTween();

    setupIconColorTween();
    
    setupBackgroundColor();

    super.didChangeDependencies();
  }

  void setupDidvierColorTween() {
    final ThemeData theme = Theme.of(context);

    Color beginColor = this.widget.dividerColor ?? theme.dividerColor;
    Color endColor = beginColor;

    switch (widget.dividerDisplayTime) {
      case DividerDisplayTime.always:
        break;
      case DividerDisplayTime.opened:
        endColor = Colors.transparent;
        break;
      case DividerDisplayTime.closed:
        beginColor = Colors.transparent;
        break;
      case DividerDisplayTime.never:
        beginColor = Colors.transparent;
        endColor = Colors.transparent;
        break;
      default:
    }
    _borderColorTween
      ..begin = beginColor
      ..end = endColor;
  }

  void setupIconColorTween(){
    final ThemeData theme = Theme.of(context);

    Color beginColor = this.widget.iconColor ?? theme.unselectedWidgetColor;
    Color endColor = beginColor;

    _iconColorTween
      ..begin = beginColor
      ..end = endColor;
  }

  void setupBackgroundColor(){
    _backgroundColorTween
    ..begin = widget.backgroundColor
    ..end = widget.backgroundColor;
  }

我不想要上方的分割線产上,所以只留了一個(gè)~任性??

 Widget _buildChildren(BuildContext context, Widget child) {
    final Color borderSideColor = _borderColor.value ?? Colors.transparent;

    return Container(
      decoration: BoxDecoration(
        color: _backgroundColor.value ?? Colors.transparent,
        border: Border(
          bottom: BorderSide(color: borderSideColor),
        ),
      ),
...

至此已修改完成~

修改后效果

調(diào)用Demo

HJExpansionTile tile = HJExpansionTile(
        title: Text(e['title']),
        children: <Widget>[_expandCell(e['values'])],
        backgroundColor: Color(0xFFF9FAFC),
        dividerColor: Color(0xFFE6E6E6),
        dividerDisplayTime: DividerDisplayTime.always, //默認(rèn)
        iconColor: Colors.grey,
      );
12039186-cd78a2e213f586cf.png
12039186-e32b4e7933f8dbaa.png

結(jié)語

本篇文章是在開發(fā)總所遇問題的總覺棵磷,如有更加方案,歡迎留言討論晋涣,學(xué)習(xí)道路永無止境仪媒,不斷學(xué)習(xí)和總結(jié)才能進(jìn)步~??

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市谢鹊,隨后出現(xiàn)的幾起案子算吩,更是在濱河造成了極大的恐慌,老刑警劉巖佃扼,帶你破解...
    沈念sama閱讀 207,248評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件偎巢,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡兼耀,警方通過查閱死者的電腦和手機(jī)压昼,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,681評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來瘤运,“玉大人窍霞,你說我怎么就攤上這事≌兀” “怎么了但金?”我有些...
    開封第一講書人閱讀 153,443評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)郁季。 經(jīng)常有香客問我冷溃,道長(zhǎng),這世上最難降的妖魔是什么梦裂? 我笑而不...
    開封第一講書人閱讀 55,475評(píng)論 1 279
  • 正文 為了忘掉前任秃诵,我火速辦了婚禮,結(jié)果婚禮上塞琼,老公的妹妹穿的比我還像新娘菠净。我一直安慰自己,他們只是感情好彪杉,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,458評(píng)論 5 374
  • 文/花漫 我一把揭開白布毅往。 她就那樣靜靜地躺著,像睡著了一般派近。 火紅的嫁衣襯著肌膚如雪攀唯。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,185評(píng)論 1 284
  • 那天渴丸,我揣著相機(jī)與錄音侯嘀,去河邊找鬼另凌。 笑死,一個(gè)胖子當(dāng)著我的面吹牛戒幔,可吹牛的內(nèi)容都是我干的吠谢。 我是一名探鬼主播,決...
    沈念sama閱讀 38,451評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼诗茎,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼工坊!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起敢订,我...
    開封第一講書人閱讀 37,112評(píng)論 0 261
  • 序言:老撾萬榮一對(duì)情侶失蹤王污,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后楚午,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體昭齐,經(jīng)...
    沈念sama閱讀 43,609評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,083評(píng)論 2 325
  • 正文 我和宋清朗相戀三年矾柜,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了司浪。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,163評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡把沼,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出吁伺,到底是詐尸還是另有隱情饮睬,我是刑警寧澤,帶...
    沈念sama閱讀 33,803評(píng)論 4 323
  • 正文 年R本政府宣布篮奄,位于F島的核電站捆愁,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏窟却。R本人自食惡果不足惜昼丑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,357評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望夸赫。 院中可真熱鬧菩帝,春花似錦、人聲如沸茬腿。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,357評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽切平。三九已至握础,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間悴品,已是汗流浹背禀综。 一陣腳步聲響...
    開封第一講書人閱讀 31,590評(píng)論 1 261
  • 我被黑心中介騙來泰國(guó)打工简烘, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人定枷。 一個(gè)月前我還...
    沈念sama閱讀 45,636評(píng)論 2 355
  • 正文 我出身青樓孤澎,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親依鸥。 傳聞我的和親對(duì)象是個(gè)殘疾皇子亥至,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,925評(píng)論 2 344

推薦閱讀更多精彩內(nèi)容