如何实现带展开/收起功能的Flutter HTML Widget?
Flutter实现HtmlWidget的「显示更多/显示更少」展开收起功能
要给flutter_widget_from_html的HtmlWidget加展开收起功能,用状态管理控制显示行数就能搞定,下面是完整实现代码:
import 'package:flutter/material.dart'; import 'package:flutter_widget_from_html/flutter_widget_from_html.dart'; class ExpandableHtmlWidget extends StatefulWidget { const ExpandableHtmlWidget({super.key}); @override State<ExpandableHtmlWidget> createState() => _ExpandableHtmlWidgetState(); } class _ExpandableHtmlWidgetState extends State<ExpandableHtmlWidget> { // 控制展开/收起状态 bool _isExpanded = false; // 收起时显示的行数,可按需调整 final int _collapsedLines = 2; @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ HtmlWidget( '''<p>We have studied the Agile methodology where Agile is a set of beliefs which should be followed to <i>develop the software development project</i>. On <h3>these beliefs or values</h3>, there is many models have developed, and in which one of the models is a <strong>scrum</strong>.We have studied the Agile methodology where Agile is a set of beliefs which should be followed to develop the software <b>development project</b>. On these beliefs or values, there is many <u>models have developed</u>, and in which one of the models is a <strong>scrum</strong>.</p>''', // 根据状态设置显示行数 maxLines: _isExpanded ? null : _collapsedLines, // 超出行数显示省略号 textStyle: const TextStyle(overflow: TextOverflow.ellipsis), ), // 切换按钮 TextButton( onPressed: () { setState(() { _isExpanded = !_isExpanded; }); }, child: Text(_isExpanded ? '显示更少' : '显示更多'), ), ], ); } }
关键说明:
- 用
StatefulWidget维护_isExpanded状态,点击按钮时切换状态刷新UI HtmlWidget的maxLines属性:收起时设为自定义行数(示例中是2行),展开时设为null显示全部内容- 通过
TextOverflow.ellipsis让超出部分显示省略号,符合展开收起的视觉逻辑 - 按钮文本随状态动态切换为「显示更多」或「显示更少」
你可以直接把这个组件嵌入页面使用,也能根据需求调整收起行数、按钮样式等细节。
内容的提问来源于stack exchange,提问作者Genius_balu
相关产品推荐
相关产品推荐

