Flutter-自定义可展开文本控件
import 'package:flutter/material.dart';
class ExpandableText extends StatefulWidget {
final String text;
final int maxLines;
final String expandText;
final String collapseText;
const ExpandableText(this.text, this.maxLines, this.expandText, this.collapseText, {Key? key}) : super(key: key);
@override
_ExpandableTextState createState() => _ExpandableTextState();
}
class _ExpandableTextState extends State<ExpandableText> {
bool _isExpanded = false;
void _toggleExpanded() {
setState(() {
_isExpanded = !_isExpanded;
});
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
ConstrainedBox(
constraints: BoxConstraints(maxHeight: _isExpanded ? double.infinity : (widget.maxLines * 1.2)), // 1.2 is an empirical coefficient to provide some buffer
child: AnimatedSize(
duration: const Duration(milliseconds: 200),
vsync: this,
child: _isExpanded ? null : Text(widget.text),
),
),
TextButton(
onPressed: _toggleExpanded,
child: Text(_isExpanded ? widget.collapseText : widget.expandText),
),
],
);
}
}
这段代码定义了一个名为ExpandableText
的有状态组件,它允许用户展开或折叠文本。组件有四个参数:text
、maxLines
、expandText
和collapseText
。maxLines
限制了文本在折叠状态下显示的最大行数,而expandText
和collapseText
是显示在按钮上的文本。组件的状态包括_isExpanded
,它记录了文本是否处于展开状态。_toggleExpanded
方法用于切换_isExpanded
的值,从而允许用户展开或折叠文本。
评论已关闭