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

零、前言

FlutterUnit是【张风捷特烈】长期维护的一个Flutter集录、指南的开源App
如果你还未食用,可参见总汇集: 【 FlutterUnit 食用指南】 开源篇

欢迎 Star。 开源地址: 点我

FlutterUnit.apk 下载FlutterUnit mac版 下载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的效果:
200ms400ms600ms
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: <Widget>[
          Row(
            children: <Widget>[
              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度

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

--

二、魔改ExpansionTile实现方案

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

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

去边线前去边线后

// 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 <Widget>[],
    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<Widget> 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<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) {

    return Container(
      color: _backgroundColor.value ?? Colors.transparent,
      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,
              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可以控制高度的分率。

ClipRect(
  child: Align(
    alignment: Alignment.topCenter,
    heightFactor: _heightFactor.value,
    child: child,
  ),
),
复制代码
默认从中间开始设置alignment: Alignment.topCenter

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

有线无线

尾声

欢迎Star和关注FlutterUnit 的发展,让我们一起携手,成为Unit一员。
另外本人有一个Flutter微信交流群,欢迎小伙伴加入,共同探讨Flutter的问题,期待与你的交流与切磋。

@张风捷特烈 2020.04.21 未允禁转
我的公众号:编程之王
联系我--邮箱:1981462002@qq.com --微信:zdl1994328
~ END ~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将一个数据库传入一个 Widget,你可以使用以下步骤: 1. 在你的数据库文件中,创建一个类来处理数据库连接和查询。 2. 在你的 Widget 中,创建一个变量来保存数据库连接。 3. 在 Widget 的 initState() 方法中,初始化数据库连接,并将数据库连接赋值给变量。 4. 在 Widget 的 dispose() 方法中,关闭数据库连接。 5. 在 Widget 中使用数据库查询方法来获取数据。 这样,你就可以在 Widget 中使用数据库了。以下是一个示例代码: ```dart import 'package:flutter/material.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; class MyDatabase { static final MyDatabase _singleton = MyDatabase._internal(); static Database _database; factory MyDatabase() { return _singleton; } MyDatabase._internal(); static Future<Database> get database async { if (_database != null) { return _database; } _database = await _initDatabase(); return _database; } static Future<Database> _initDatabase() async { String databasesPath = await getDatabasesPath(); String path = join(databasesPath, 'my_database.db'); return openDatabase( path, version: 1, onCreate: (Database db, int version) async { await db.execute( 'CREATE TABLE my_table (id INTEGER PRIMARY KEY, name TEXT)', ); }, ); } static Future<List<Map<String, dynamic>>> query(String sql) async { Database db = await MyDatabase.database; return db.rawQuery(sql); } } class MyWidget extends StatefulWidget { @override _MyWidgetState createState() => _MyWidgetState(); } class _MyWidgetState extends State<MyWidget> { Database _database; @override void initState() { super.initState(); _initDatabase(); } void _initDatabase() async { _database = await MyDatabase.database; } @override void dispose() { _database.close(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('My Widget'), ), body: Center( child: FutureBuilder<List<Map<String, dynamic>>>( future: MyDatabase.query('SELECT * FROM my_table'), builder: (BuildContext context, AsyncSnapshot<List<Map<String, dynamic>>> snapshot) { if (snapshot.hasData) { return ListView.builder( itemCount: snapshot.data.length, itemBuilder: (BuildContext context, int index) { return ListTile( title: Text(snapshot.data[index]['name']), ); }, ); } else if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return CircularProgressIndicator(); } }, ), ), ); } } ``` 在这个示例代码中,我们创建了一个 MyDatabase 类来处理数据库连接和查询。在 MyWidget 中,我们使用 initState() 方法来初始化数据库连接,并使用 dispose() 方法来关闭数据库连接。在 build() 方法中,我们使用 FutureBuilder 来获取数据库查询结果,并将结果显示在 ListView 中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值