Flutter中Row组件嵌套多行文本与Read More换行溢出问题求助
Flutter 实现多行文本末尾紧跟“Read More”并点击弹出BottomSheet
直接用Row组件肯定不行——Row是单行布局,没法适配多行文本的排版需求。推荐用RichText组件来实现,它可以把不同样式、可点击的文本片段组合在一起,完美解决你的问题。
完整实现代码
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; class ReadMoreText extends StatefulWidget { const ReadMoreText({super.key}); @override State<ReadMoreText> createState() => _ReadMoreTextState(); } class _ReadMoreTextState extends State<ReadMoreText> { late TapGestureRecognizer _readMoreRecognizer; @override void initState() { super.initState(); _readMoreRecognizer = TapGestureRecognizer() ..onTap = () { showModalBottomSheet( context: context, builder: (context) => const SizedBox( height: 200, child: Center( child: Text('这里是BottomSheet内容'), ), ), ); }; } @override void dispose() { _readMoreRecognizer.dispose(); // 释放资源,避免内存泄漏 super.dispose(); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(16.0), child: RichText( text: TextSpan( style: DefaultTextStyle.of(context).style, children: [ const TextSpan( text: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. ', ), TextSpan( text: 'Read More...', style: const TextStyle(color: Colors.blue, fontWeight: FontWeight.bold), recognizer: _readMoreRecognizer, ), ], ), ), ); } }
关键说明
RichText:用来组合多个TextSpan,支持多行排版,“Read More”会自动紧跟在普通文本的最后一行末尾,不会出现换行溢出。TapGestureRecognizer:给“Read More”文本添加点击事件,点击后调用showModalBottomSheet弹出底部弹窗。- 资源释放:在组件销毁时调用
_readMoreRecognizer.dispose(),避免内存泄漏。
内容的提问来源于stack exchange,提问作者fazilSizzlers
相关产品推荐
相关产品推荐

