如何在flutter_markdown开启selectable:true时调整行高?
问题描述
我编写了如下最小示例代码:
import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Markdown( selectable: true, styleSheet: MarkdownStyleSheet.fromTheme(ThemeData( textTheme: const TextTheme( bodyText2: TextStyle(height: 1.2, fontSize: 14.0)))), data: 'one\n\ntwo\n\nthree')); } }
开启selectable: true时,行间距约为正常的4倍;调整height等样式属性无法修复该问题,但将selectable设为false后行间距恢复正常,height属性也能正常生效。已在Linux和Chrome环境测试,结果一致,使用的flutter_markdown版本为^0.6.10+4。请问如何在保持selectable: true的情况下调整行高?
解决方案
问题根源在于flutter_markdown开启可选文本时,会将段落包装在SelectableText组件中,此时通过MarkdownStyleSheet.fromTheme传入的bodyText2样式无法正确传递给SelectableText的行高设置。可以通过直接指定MarkdownStyleSheet的p属性来设置段落行高,绕过主题样式传递的问题。
修改后的代码如下:
import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Markdown( selectable: true, styleSheet: MarkdownStyleSheet( p: const TextStyle(height: 1.2, fontSize: 14.0), ), data: 'one\n\ntwo\n\nthree')); } }
如果需要基于主题样式进行扩展,可以先通过fromTheme获取基础样式,再覆盖p属性:
styleSheet: MarkdownStyleSheet.fromTheme(ThemeData( primarySwatch: Colors.blue, )).copyWith( p: const TextStyle(height: 1.2, fontSize: 14.0), ),
这样设置后,即使selectable为true,段落的行高也会正常生效。
内容的提问来源于stack exchange,提问作者bitinerant
相关产品推荐
相关产品推荐

