在Flutter开发中,其实系统已经给我们提供了一个可靠的二级列表展开的API(ExpansionPanelList
),我们先看系统的二级列表展开效果,一次只能展开一个,用ExpansionPanelList.radio
实现
由此可见,已经能很大部分满足我们的需求了,
但是…在使用过程中,我发现无法改变右侧icon的位置,或者是想隐藏icon,只能改其颜色
expandIconColor: Colors.white,
但是,这个时候cell的点击事件只有下图中黄色区域
如果想让整个cell都能被点击,只能设置
canTapOnHeader: true,
但是,如果设置了这个属性,改变icon颜色的这个expandIconColor
就失效了,所有在使用过程中,不能很好的耦合自身项目需求,而我们的项目,是要让icon紧挨着在text的后面,如下图
查阅了很多资料,如果使用系统提供的API,不能实现项目中想要的效果,无奈只能自己造轮子了,实现效果如下
使用自定义的,自己想怎么布局就怎么布局,没那么多耦合性,下面直接贴出代码,文章末尾会贴出系统和自定义两种方法分别实现的demo
先开系统实现、代码里面都标准了注释,这里就不一一赘述了,如果有什么问题,欢迎下方留言
import 'dart:convert';import 'package:demo/model/model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';class SecondListPage extends StatefulWidget {const SecondListPage({super.key});@overrideState<SecondListPage> createState() => _SecondListPageState();
}class _SecondListPageState extends State<SecondListPage> {final List<ListModel> _dataList = [];@overridevoid initState() {super.initState();_loadData();}_loadData() async {_dataList.clear();String jsonString = await rootBundle.loadString('assets/json/list.json');Map<String, dynamic> dict = jsonDecode(jsonString);_dataList.addAll(dict['data'].map<ListModel>((e) => ListModel.fromJson(e)).toList());setState(() {});}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text('系统二级列表'),),body: SingleChildScrollView(child: Container(child: _buildExpansionPanel(),),),);}Widget _buildExpansionPanel() {return ExpansionPanelList.radio(initialOpenPanelValue: _dataList[0].id, //默认展开第一个expandIconColor:Colors.white, //设置icon的颜色,因为设置了canTapOnHeader: true,所以这里无效dividerColor: const Color.fromARGB(0, 233, 219, 219),expandedHeaderPadding: const EdgeInsets.all(0),materialGapSize: 0,// 设置底部阴影大小elevation: 0,children: _dataList.map<ExpansionPanelRadio>((item) {return ExpansionPanelRadio(canTapOnHeader: true, //点击区域backgroundColor: Colors.red,value: item.id!, //唯一标识headerBuilder: (context, isExpanded) {return Container(padding: const EdgeInsets.all(16.0),child: Text(item.title!,style: const TextStyle(color: Colors.white,),),);},body: ListView.builder(padding: const EdgeInsets.all(0),shrinkWrap: true,physics: const NeverScrollableScrollPhysics(),itemCount: item.subData!.length,itemExtent: 76.0,itemBuilder: (context, index) {return Container(color: Colors.green,child: ListTile(title: Text(item.subData![index].title!),),);},),);}).toList(),);}
}
自定义实现代码
import 'dart:convert';import 'package:demo/model/model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';class SecondListViewPage extends StatefulWidget {const SecondListViewPage({super.key});@overrideState<SecondListViewPage> createState() => _SecondListViewPageState();
}class _SecondListViewPageState extends State<SecondListViewPage> {final List<ListModel> _dataList = []; //列表数据List listData = []; //处理是否展开和展开动画的数据final bool _isRadio = true; //是否只展开一个,默认是final double _cellHeight = 40.0; //title的高度final double _itemHeight = 40.0; //展开的cell的高度@overridevoid initState() {super.initState();_loadData();}@overridevoid dispose() {for (var listItem in listData) {listItem.animationController.dispose();}super.dispose();}_loadData() async {_dataList.clear();String jsonString = await rootBundle.loadString('assets/json/list.json');Map<String, dynamic> dict = jsonDecode(jsonString);_dataList.addAll(dict['data'].map<ListModel>((e) => ListModel.fromJson(e)).toList());for (var i = 0; i < _dataList.length; i++) {ListItem item = ListItem();//处理数据,给每个cell都新增一个isExpended属性item.isExpanded = i == 0 ? true : false; //默认第一个展开if (i == 0) {item.animationController.forward(); //第一个默认展开之后需要改变图片的旋转方向}listData.add(item);}setState(() {});}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text('自定义二级列表'),),body: ListView.builder(itemCount: _dataList.length,itemBuilder: (context, index) {ListItem item = listData[index];return Column(children: [GestureDetector(onTap: () {setState(() {item.isExpanded = !item.isExpanded;if (_isRadio) {for (var i = 0; i < listData.length; i++) {if (i != index) {listData[i].isExpanded = false;}if (listData[i].isExpanded) {listData[i].animationController.forward();} else {listData[i].animationController.reverse();}}} else {if (listData[index].isExpanded) {listData[index].animationController.forward();} else {listData[index].animationController.reverse();}}});},child: Container(padding: const EdgeInsets.all(10.0),color: Colors.green,height: _cellHeight,child: Row(children: [// 显示title的widget,可以自定义Text('${_dataList[index].title}'),const SizedBox(width: 5.0),AnimatedBuilder(animation: item.animation,builder: (context, child) {return Transform.rotate(angle: item.animation.value * 3.14, // 180度对应的弧度值child: const Icon(Icons.arrow_drop_down), //这里可以替换成自定义的图片);},),],),),),AnimatedContainer(color: Colors.yellow,duration: const Duration(milliseconds: 200),height: item.isExpanded? _dataList[index].subData!.length * _itemHeight: 0.0,child: item.isExpanded? SingleChildScrollView(child: Column(children: _dataList[index].subData!.map((e) {return Container(alignment: Alignment.centerLeft,height: _itemHeight,child: Text(e.title!),);}).toList(),),): null,),],);},),);}
}class ListItem {bool isExpanded; //是否展开AnimationController animationController; //每个title展开或者关闭的时候,icon的旋转动画late Animation<double> animation; //ListItem({this.isExpanded = false}): animationController = AnimationController(duration: const Duration(milliseconds: 200),vsync: TickerProviderImpl(),) {animation = Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(parent: animationController,curve: Curves.easeInOut,),);}
}class TickerProviderImpl extends TickerProvider {@overrideTicker createTicker(TickerCallback onTick) {return Ticker(onTick);}
}
简书传送门
GitHub传送门