Flutter显示markdown中的代码高亮

众所周知,程序员写博客一般都是使用markdown格式。

今天遇到一个需求,在flutter上显示markdown文件。盲猜flutter肯定有markdown的库

pub上一搜,果然有

安装flutter_markdown

flutter_markdown: ^0.6.14

使用flutter_markdown

const Markdown(data: "# hello")

只需要一句话,就可以让markdown格式化显示在屏幕上了。

如何使用代码高亮呢?

flutter_markdown这个库,默认没有实现代码高亮,就一个很朴素的白底黑字。

这时候就需要使用到另外两个库

  markdown:
  flutter_highlighter: ^0.1.1
  

实现MarkdownElementBuilder



import 'package:flutter/material.dart';
import 'package:flutter_highlighter/flutter_highlighter.dart';
import 'package:flutter_highlighter/themes/github.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:markdown/markdown.dart' as md;

class CodeHightLightView extends StatefulWidget {
  final String content;

  final String lang;

  const CodeHightLightView(
      {super.key, required this.content, required this.lang});

  @override
  State<CodeHightLightView> createState() => _CodeHightLightViewState();
}

class _CodeHightLightViewState extends State<CodeHightLightView> {
  @override
  Widget build(BuildContext context) {
    return HighlightView(
      // The original code to be highlighted
      widget.content,

      // Specify language
      // It is recommended to give it a value for performance
      language: widget.lang,

      // Specify highlight theme
      // All available themes are listed in `themes` folder
      theme: githubTheme,

      // Specify padding
      padding: const EdgeInsets.all(8),

      // Specify text style
      textStyle: const TextStyle(
        fontSize: 14,
      ),
    );
  }
}

class CodeElementBuilder extends MarkdownElementBuilder {
  @override
  Widget? visitElementAfter(md.Element element, TextStyle? preferredStyle) {
    var language = '';
    if (element.attributes['class'] != null) {
      String lg = element.attributes['class'] as String;
      language = lg.substring(9);
    }
    return CodeHightLightView(
      content: element.textContent,
      lang: language,
    );
  }
}

注册这个builder到markdown库

builders: {"code": CodeElementBuilder()},

到此,就可以正常高亮显示markdown中的代码了。

image

欢迎和我交流flutter的技术,我的博客园主页 https://www.cnblogs.com/boxrice/

posted on 2023-04-26 00:18  快乐海盗  阅读(964)  评论(0编辑  收藏  举报