前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【 Flutter Unit 解牛篇 】代码折叠展开面板,怎么没有线?

【 Flutter Unit 解牛篇 】代码折叠展开面板,怎么没有线?

作者头像
张风捷特烈
发布2020-10-16 11:06:59
1.8K0
发布2020-10-16 11:06:59
举报
零、前言

FlutterUnit是【张风捷特烈】长期维护的一个Flutter集录、指南的开源App

如果你还未食用,可参见总汇集: 【 FlutterUnit 食用指南】 开源篇

欢迎 Star。 开源地址: 点我

FlutterUnit.apk 下载
FlutterUnit.apk 下载
FlutterUnit mac版 下载
FlutterUnit mac版 下载
Github仓库地址
Github仓库地址

Flutter Unit 解牛篇 将对项目的一些实现点进行剖析。 很多朋友问我,你代码折叠面板怎么做的?ExpansionTile展开的线去不掉吧? 确实ExpansionTile展开上下会有线,非常难看,所以我未使用ExpansionTile方案 折叠效果的核心代码在源码的: components/project/widget_node_panel.dart

.

.

.

.
.
.
.
.
.

一、AnimatedCrossFade实现方案

核心的组件是: AnimatedCrossFade,可能很少人用,但它是一个十分强大的组件 你可以在FlutterUnit app中进行搜索体验。

.

.

.

.

.
.
.
.
.
.
.
.

1. AnimatedCrossFade的基本用法
  • AnimatedCrossFade可以包含两个组件firstChildsecondChild
  • 可指定枚举状态量crossFadeState,有两个值showFirstshowSecond
  • 当状态量改变时,会根据状态显示第一个或第二个。切换时会淡入淡出。
  • 可以指定动画时长。如下分别是200ms,400ms,600ms的效果:

200ms

400ms

600ms

200ms
200ms
400ms
400ms
600ms
600ms
代码语言:javascript
复制
class TolyExpandTile extends StatefulWidget {

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

class _TolyExpandTileState extends State<TolyExpandTile>
    
    with SingleTickerProviderStateMixin {
  var _crossFadeState = CrossFadeState.showFirst;

  bool get isFirst => _crossFadeState == CrossFadeState.showFirst;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(20),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: Container(),
              ),
              GestureDetector(
                  onTap: _togglePanel,
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Icon(Icons.code),
                  ))
            ],
          ),
          _buildPanel()
        ],
      ),
    );
  }

  void _togglePanel() {
    setState(() {
      _crossFadeState =
          !isFirst ? CrossFadeState.showFirst : CrossFadeState.showSecond;
    });
  }

  Widget _buildPanel() => AnimatedCrossFade(
        firstCurve: Curves.easeInCirc,
        secondCurve: Curves.easeInToLinear,
        firstChild: Container(),
        secondChild: Container(
          height: 150,
          color: Colors.blue,
        ),
        duration: Duration(milliseconds: 300),
        crossFadeState: _crossFadeState,
      );
}
复制代码

2. 和ToggleRotate联用

ToggleRotate是我写的一个非常小的组件包, toggle_rotate: ^0.0.5 用于点击时组件自动旋转转回的切换。详见文章: toggle_rotate

45度

90度

45度
45度
90度
90度

Flutter Unit基本就是根据这种方法实现的代码面板折叠。

-

-

-
-
-
-

二、魔改ExpansionTile实现方案

上周六晚8:30B站直播了ExpansionTile源码的解析。 只要看懂源码,其实魔改一下也是so easy 的。核心就是下面border的锅 注释掉即可, 你也可以修改其中的_kExpand常量来控制动画的时长。

注意: 一切对源码的魔改,都需要拷贝出来,新建文件,别直接改源码。 下面的代码是处理之后的,可以拿去直接用

去边线前

去边线后

去边线前
去边线前
去边线后
去边线后

代码语言:javascript
复制
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

const Duration _kExpand = Duration(milliseconds: 200);

class NoBorderExpansionTile extends StatefulWidget {

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

  final Widget leading;
  
  final Widget title;

  final Widget subtitle;
  
  final ValueChanged<bool> onExpansionChanged;
  
  final List children;

  final Color backgroundColor;

  final Widget trailing;

  final bool initiallyExpanded;

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

class _ExpansionTileState extends State<ExpansionTile> 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 _borderColor;
  Animation _headerColor;
  Animation _iconColor;
  Animation _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) {

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

  @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();
  }

  @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),
    );
  }
}
复制代码

直播中说了ExpansionTile的核心实现是通过ClipRectAlign 没错,又是神奇的Align,它的heightFactor可以控制高度的分率。

代码语言:javascript
复制
ClipRect(
  child: Align(
    alignment: Alignment.topCenter,
    heightFactor: _heightFactor.value,
    child: child,
  ),
),

默认从中间开始

设置alignment: Alignment.topCenter

默认从中间开始
默认从中间开始
设置alignment: Alignment.topCenter
设置alignment: Alignment.topCenter

这样就能控制从哪里出现。还是那句话: 源码在手,天下我有。没事多看看源码的实现,对自己是很有帮助的。这也是直播源码之间的初衷,别再问什么学习方法了,学会debug,然后逼自己看源码是最快的成长方式。

有线

无线

有线
有线
无线
无线
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 零、前言
  • 一、AnimatedCrossFade实现方案
    • 1. AnimatedCrossFade的基本用法
    • 2. 和ToggleRotate联用
    • 二、魔改ExpansionTile实现方案
    相关产品与服务
    云直播
    云直播(Cloud Streaming Services,CSS)为您提供极速、稳定、专业的云端直播处理服务,根据业务的不同直播场景需求,云直播提供了标准直播、快直播、云导播台三种服务,分别针对大规模实时观看、超低延时直播、便捷云端导播的场景,配合腾讯云视立方·直播 SDK,为您提供一站式的音视频直播解决方案。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档