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