You can add code syntax highlighter to flutter_markdown by using the flutter_highlight package. Follow the steps below to implement syntax highlighting:
-
Add the flutter_highlight dependency to your pubspec.yaml file:
dependencies: flutter_highlight: ^0.6.0
-
Import the required packages in your dart file:
import 'package:flutter_highlight/flutter_highlight.dart'; import 'package:flutter_markdown/flutter_markdown.dart';
-
Create a list of MarkdownSyntaxHighlighter objects:
final List<MarkdownSyntaxHighlighter> _highlighters = [ FlutterHighlighter(), ];
-
Define the FlutterHighlighter class:
class FlutterHighlighter extends SyntaxHighlighter { @override TextSpan format(String source) { return TextSpan( children: <TextSpan>[ TextSpan( text: source, style: TextStyle(color: Colors.blue), ), ], ); } }
Note: This is just a basic implementation of the FlutterHighlighter class. You can customize it to support different programming languages.
-
Finally, use the Markdown widget and pass the _highlighters list as a parameter:
Markdown( data: """ ```dart // Your Dart code ``` """, syntaxHighlighter: new MultiSyntaxHighlighter(_highlighters), )
Note: You need to specify the language of the code block (e.g.
dart
in the above example) to enable syntax highlighting.
That's it! You can now see syntax highlighting in your code snippets using flutter_markdown.