做为源码浅析系列的文章,我想说一下:canvas
我发现不少人对于各类 widget 的使用不是很理解,常常会在群里问一些比较简单的问题,例如 TextField 如何监听确认按钮。ide
而关于Flutter 中控件的使用及实现方式,其实只要耐下心来好好的看一下它的构造函数和源码,都能看得懂。函数
并且我打算这个系列也不会讲的很深,也就是围绕这两点:一、构造函数 二、实现方式。学习
其实关于 DropdownButton
的构造函数和简单使用我在上一篇文章中已经有过讲解,动画
若有不懂怎么用的,能够看这篇文章:Flutter DropdownButton简单使用及魔改源码。ui
下面重点说一下 DropdownButton
是如何实现的。this
咱们须要带着以下几个问题去看源码:lua
带着如上问题,咱们开始。spa
咱们在上一篇文章中已经了解到,DropdownButton 是一个 statefulWidget,那咱们想要了解他是如何实现的,就直接跳转到他的 _DropdownButtonState 类中。code
二话不说,直接找到 build(BuildContext context)
方法。
先看看 return 了个什么:
return Semantics(
button: true,
child: GestureDetector(
onTap: _enabled ? _handleTap : null,
behavior: HitTestBehavior.opaque,
child: result,
),
);
复制代码
能够看到返回了一个 Semantics
,这个控件简单来讲就是用于视障人士的,对于咱们正常APP来讲可用可不用,若是是特殊的APP,那么建议使用。
而后下面 child 返回了一个手势:
handleTap
方法,若是不可用就算了。HitTestBehavior.opaque
为不透明的能够被选中不看点击方法,先来找到 result:
Widget result = DefaultTextStyle(
style: _textStyle,
child: Container(
padding: padding.resolve(Directionality.of(context)),
height: widget.isDense ? _denseButtonHeight : null,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
widget.isExpanded ? Expanded(child: innerItemsWidget) : innerItemsWidget,
IconTheme(
data: IconThemeData(
color: _iconColor,
size: widget.iconSize,
),
child: widget.icon ?? defaultIcon,
),
],
),
),
);
复制代码
咱们能够看到,其实result 最终是一个 Row,里面一共有两个 widget:
样子以下:
其中 One 就是 innerItemsWidget
,箭头就是 Icon。
并且 innerItemsWidget
判断了是不是展开状态,若是是展开状态则套一个 Expanded 来水平填充父级。
接着往上面找:
// 若是值为空(则_selectedindex为空),或者若是禁用,则显示提示或彻底不显示。
final int index = _enabled ? (_selectedIndex ?? hintIndex) : hintIndex;
Widget innerItemsWidget;
if (items.isEmpty) {
innerItemsWidget = Container();
} else {
innerItemsWidget = IndexedStack(
index: index,
alignment: AlignmentDirectional.centerStart,
children: items,
);
}
复制代码
从这咱们能够看得出来,innerItemsWidget
是一个 IndexedStack
,
它把全部的 item 都罗列到了一块儿,用 index 来控制展现哪个。
那看到这咱们也就明白了,其实 DropdownButton
就是一个 IndexedStack
。
那这样来讲,主要的逻辑应该在点击事件里。
上面咱们在 return 的时候看到了,在 onTap 的时候调用的是 _handleTap()
方法。
那咱们直接来看一下:
void _handleTap() {
final RenderBox itemBox = context.findRenderObject();
final Rect itemRect = itemBox.localToGlobal(Offset.zero) & itemBox.size;
final TextDirection textDirection = Directionality.of(context);
final EdgeInsetsGeometry menuMargin = ButtonTheme.of(context).alignedDropdown
?_kAlignedMenuMargin
: _kUnalignedMenuMargin;
assert(_dropdownRoute == null);
_dropdownRoute = _DropdownRoute<T>(
items: widget.items,
buttonRect: menuMargin.resolve(textDirection).inflateRect(itemRect),
padding: _kMenuItemPadding.resolve(textDirection),
selectedIndex: 0,
elevation: widget.elevation,
theme: Theme.of(context, shadowThemeOnly: true),
style: _textStyle,
barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
);
Navigator.push(context, _dropdownRoute).then<void>((_DropdownRouteResult<T> newValue) {
_dropdownRoute = null;
if (!mounted || newValue == null)
return;
if (widget.onChanged != null)
widget.onChanged(newValue.result);
});
}
复制代码
首先上面定义了几个 final 的变量,这些变量就是一些参数,见名知意。
后面重点来了:
_DropdownRoute
首先咱们来看一下 _DropdownRoute
,上篇文章魔改代码的时候也已经说过,
_DropdownRoute
继承自 PopupRoute
,是一个浮在当前页面上的 route。
而后咱们找到他 buildPage
方法:
@override
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return _DropdownRoutePage<T>(
route: this,
constraints: constraints,
items: items,
padding: padding,
buttonRect: buttonRect,
selectedIndex: selectedIndex,
elevation: elevation,
theme: theme,
style: style,
);
}
);
}
复制代码
能够看到这里是返回了一个 LayoutBuilder
。
LayoutBuilder
最有用的是他能够知道该父级的大小和约束,经过该约束咱们就能够作一些操做。
而且咱们也看到确实是给 _DropdownRoutePage
传入了 constraints .
如上,_DropdownRoute
返回了 _DropdownRoutePage
,那下面就来看一下它,
_DropdownRoutePage
是一个无状态的小部件,咱们也是直接来看一下 build 方法的 return:
return MediaQuery.removePadding(
context: context,
removeTop: true,
removeBottom: true,
removeLeft: true,
removeRight: true,
child: Builder(
builder: (BuildContext context) {
return CustomSingleChildLayout(
delegate: _DropdownMenuRouteLayout<T>(
buttonRect: buttonRect,
menuTop: menuTop,
menuHeight: menuHeight,
textDirection: textDirection,
),
child: menu,
);
},
),
);
复制代码
首先 MediaQuery.removePadding
是建立一个给定的 context 的 MediaQuery,可是删除了 padding。最后经过 CustomSingleChildLayout
返回了 menu
。
其中 delegate 为自定义的 _DropdownMenuRouteLayout
,这里主要是给定一些约束和控制了位置,这里不在本节内容当中,因此不过多的讲解。
到这里点击的逻辑就结束了,主要就是弹出了一个 PopupRoute
。
上面能够看到在点击的时候跳转到了 _DropdownRoute
,而 _DropdownRoute
最终返回了一个 _DropdownMenu
。
_DropdownMenu
是一个有状态的小部件,那咱们直接看它的 _State.
仍是找到 build 方法,看一下都返回了什么:
return FadeTransition(
opacity: _fadeOpacity,
child: CustomPaint(
painter: _DropdownMenuPainter(
color: Theme.of(context).canvasColor,
elevation: route.elevation,
selectedIndex: route.selectedIndex,
resize: _resize,
),
child: Semantics(
scopesRoute: true,
namesRoute: true,
explicitChildNodes: true,
label: localizations.popupMenuLabel,
child: Material(
type: MaterialType.transparency,
textStyle: route.style,
child: ScrollConfiguration(
behavior: const _DropdownScrollBehavior(),
child: Scrollbar(
child: ListView(
controller: widget.route.scrollController,
padding: kMaterialListPadding,
itemExtent: _kMenuItemHeight,
shrinkWrap: true,
children: children,
),
),
),
),
),
),
);
复制代码
首先是返回了一个自定义组件,自定义组件里的逻辑是:根据当前选中的 index 来画展开的方框:
就是外面带阴影的那个框。
代码以下:
@override
void paint(Canvas canvas, Size size) {
final double selectedItemOffset = selectedIndex * _kMenuItemHeight + kMaterialListPadding.top;
final Tween<double> top = Tween<double>(
begin: selectedItemOffset.clamp(0.0, size.height - _kMenuItemHeight),
end: 0.0,
);
final Tween<double> bottom = Tween<double>(
begin: (top.begin + _kMenuItemHeight).clamp(_kMenuItemHeight, size.height),
end: size.height,
);
final Rect rect = Rect.fromLTRB(0.0, top.evaluate(resize), size.width, bottom.evaluate(resize));
_painter.paint(canvas, rect.topLeft, ImageConfiguration(size: rect.size));
}
复制代码
这里就很少说,有兴趣的能够自行看一下。
而后最终返回了一个 ListView,咱们能够去看一下这个 children:
final List<Widget> children = <Widget>[];
for (int itemIndex = 0; itemIndex < route.items.length; ++itemIndex) {
CurvedAnimation opacity;
if (itemIndex == route.selectedIndex) {
opacity = CurvedAnimation(parent: route.animation, curve: const Threshold(0.0));
} else {
final double start = (0.5 + (itemIndex + 1) * unit).clamp(0.0, 1.0);
final double end = (start + 1.5 * unit).clamp(0.0, 1.0);
opacity = CurvedAnimation(parent: route.animation, curve: Interval(start, end));
}
children.add(FadeTransition(
opacity: opacity,
child: InkWell(
child: Container(
padding: widget.padding,
child: route.items[itemIndex],
),
onTap: () => Navigator.pop(
context,
_DropdownRouteResult<T>(route.items[itemIndex].value),
),
),
));
}
复制代码
children
当中最主要的逻辑有三个:
Navigator.pop
来返回选中的值到这里咱们就把 material/dropdown.dart
中全部的代码看了一遍。
把源码看完,咱们能够来进行总结一下:
经过查看源码,咱们是否是能够进行触类旁通:
其实我的认为,查看源码,不只仅能够学到当前组件是如何实现的,
并且在查看源码的过程当中,会遇到很是多的问题,这些问题都会促使咱们去查文档,查资料,
这难道不也是一个学习的过程么。