Flutter之ExpansionTile实现以代码方式码折叠、展开

简介: Flutter之ExpansionTile实现以代码方式码折叠、展开

Flutter自带的ExpansionTile只能通过点击标题触发展开和折叠,有时候我们想要以代码的方式控制,那满足不了我们的需求。我们只能修改源码。


复制源码

复制ExpansionTile的源码到一个新的dart文件中,比如CustomExpansionTile。修改类名

// Copyright 2014 The Flutter 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';

const Duration _kExpand = Duration(milliseconds: 200);

/// A single-line [ListTile] with an expansion arrow icon 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
/// [ExpansionTile] to save and restore its expanded state when it is scrolled
/// in and out of view.
///
/// This class overrides the [ListTileThemeData.iconColor] and [ListTileThemeData.textColor]
/// theme properties for its [ListTile]. These colors animate between values when
/// the tile is expanded and collapsed: between [iconColor], [collapsedIconColor] and
/// between [textColor] and [collapsedTextColor].
///
/// The expansion arrow icon is shown on the right by default in left-to-right languages
/// (i.e. the trailing edge). This can be changed using [controlAffinity]. This maps
/// to the [leading] and [trailing] properties of [ExpansionTile].
///
/// {@tool dartpad}
/// This example demonstrates different configurations of ExpansionTile.
///
/// ** See code in examples/api/lib/material/expansion_tile/expansion_tile.0.dart **
/// {@end-tool}
///
/// See also:
///
///  * [ListTile], useful for creating expansion tile [children] when the
///    expansion tile represents a sublist.
///  * The "Expand and collapse" section of
///    <https://material.io/components/lists#types>
class CustomExpansionTile extends StatefulWidget {
  /// Creates a single-line [ListTile] with an expansion arrow icon that expands or collapses
  /// the tile to reveal or hide the [children]. The [initiallyExpanded] property must
  /// be non-null.
  const CustomExpansionTile(...);
  /// 代码太长省略....
}

class ExpansionTileState extends State<CustomExpansionTile> with SingleTickerProviderStateMixin {
  /// 代码太长省略....
}

因为使用的时候需要使用context来获取到State,必须去掉下划线.

/// _ExpansionTileState改为ExpansionTileState
class ExpansionTileState extends State<CustomExpansionTile> with SingleTickerProviderStateMixin{
  .....
}


增加2个方法用来展开、折叠

在State中,有一个变量_isExpanded,保存的是当前状态。

有一个方法_handleTap(),是处理点击事情的,折叠时点击会自动展开,展开时点击会自动折叠了。

所以我们只需要在适当的时候调用_handleTap()即可。

  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);
    });
    widget.onExpansionChanged?.call(_isExpanded);
  }

添加2个方法

/// 折叠
void collapse(){
  if(_isExpanded){
    /// 只有在展开状态下才会触发
    _handleTap();
  }
}
/// 展开
void expand(){
  if(!_isExpanded){
    /// 只有在折叠状态下才会触发
    _handleTap();
  }
}

使用

首先,创建一个GlobalKey.

/// 记得加上泛型
GlobalKey<ExpansionTileState> expansionKey = GlobalKey();

将key传递给我们自定义的CustomExpansionTile

ExpansionTile(key: expansionKey,title: Text('我是标题'),children: [
  Container(
    height: 300,
    child: Center(
      child: Text('这是展开的内容'),
    ),
  ),
],),


需要展开或者折叠的时候使用key获取到state后调用方法

/// 展开
expansionKey.currentState!.expand();
/// 折叠
expansionKey.currentState!.collapse();


相关文章
|
Dart Linux API
Flutter 上使用 C/C++ 代码(上)
Flutter 上使用 C/C++ 代码(上)
2924 0
Flutter 上使用 C/C++ 代码(上)
|
2月前
|
Dart
Flutter笔记:手动配置VSCode中Dart代码自动格式化
Flutter笔记:手动配置VSCode中Dart代码自动格式化
174 5
|
5月前
|
Dart 安全
简化代码、提高效率:Dart和Flutter开发小技巧
在日常开发中,我们常常会使用一些常用的技巧或语法糖,以简化代码、提高开发效率。本文将分享一些在Dart和Flutter中常用的小贴士,帮助你更轻松地编写优雅高效的代码。
简化代码、提高效率:Dart和Flutter开发小技巧
|
5月前
|
Dart 前端开发 Android开发
【Flutter前端技术开发专栏】Flutter中的平台特定代码实现
【4月更文挑战第30天】Flutter旨在实现跨平台移动应用开发,但有时需针对iOS或Android编写特定代码。平台通道是关键机制,允许Dart代码与原生代码交互。通过`MethodChannel`等实现跨平台通信,然后在iOS和Android上响应调用。条件编译则在编译时决定特定平台代码。本文展示了如何在Flutter中处理平台特定功能,包括示例代码和总结。
112 0
【Flutter前端技术开发专栏】Flutter中的平台特定代码实现
|
5月前
|
Dart 前端开发 Android开发
【Flutter前端技术开发专栏】Flutter与原生代码的集成与交互
【4月更文挑战第30天】本文探讨了如何在Flutter中集成和交互原生代码,以利用特定平台的API和库。当需要访问如蓝牙、特定支付SDK或复杂动画时,集成原生代码能提升效率和性能。集成方法包括:使用Platform Channel进行通信,借助现有Flutter插件,以及Android和iOS的Embedding。文中通过一个电池信息获取的例子展示了如何使用`MethodChannel`在Dart和原生代码间传递调用。这些技术使开发者能充分利用原生功能,加速开发进程。
89 0
【Flutter前端技术开发专栏】Flutter与原生代码的集成与交互
|
5月前
|
存储 Dart 前端开发
为什么说 Compose 的声明式代码最简洁 ?Compose/React/Flutter/SwiftUI 语法对比
为什么说 Compose 的声明式代码最简洁 ?Compose/React/Flutter/SwiftUI 语法对比
181 1
|
12月前
|
存储 Dart 前端开发
原来Flutter代码是这样运行在原生系统的!快来了解Flutter标准模板,感受原生系统中Flutter的魅力!
原来Flutter代码是这样运行在原生系统的!快来了解Flutter标准模板,感受原生系统中Flutter的魅力!
77 0
|
开发框架 Dart 开发工具
使用Flutter开发一套可同时运行在Android和iOS平台的代码
Flutter是一种跨平台移动应用开发框架,它允许开发者使用单一代码库构建高性能、美观且可在多个平台上运行的应用程序。本文将介绍如何使用Flutter开发一套同时适用于Android和iOS平台的代码。
|
Dart 监控 Java
Flutter和原生代码的通信
我们只用Flutter实现了一个页面,现有的大量逻辑都是用Java实现,在运行时会有许多场景必须使用原生应用中的逻辑和功能,例如网络请求
Flutter和原生代码的通信
下一篇
无影云桌面