Syntax Highlighting

Code blocks are highlighted automatically. Use codeBuilder to replace the default renderer with your own widget.

Default behaviour

Fenced code blocks with a language identifier are highlighted out of the box — no configuration needed.

example.dart
1// Syntax highlighting works out of the box. 2// Just include a fenced code block in your Markdown: 3GptMarkdown(r''' 4```dart 5void main() { 6 print('Hello, world!'); 7} 8``` 9 10```python 11def greet(name): 12 return f"Hello, {name}!" 13``` 14''')

Custom code block renderer

The codeBuilder callback receives the language name, raw code string, and a closed flag — return any widget you like.

custom_code_block.dart
1import 'package:flutter/material.dart'; 2import 'package:gpt_markdown/gpt_markdown.dart'; 3 4GptMarkdown( 5 content, 6 // name = language identifier (e.g. "dart", "python", "js") 7 // code = the raw code string 8 // closed = false while streaming (incomplete fence), true when done 9 codeBuilder: (context, name, code, closed) { 10 return Container( 11 width: double.infinity, 12 decoration: BoxDecoration( 13 color: const Color(0xFF1E1E1E), 14 borderRadius: BorderRadius.circular(8), 15 ), 16 padding: const EdgeInsets.all(16), 17 child: Column( 18 crossAxisAlignment: CrossAxisAlignment.start, 19 children: [ 20 if (name.isNotEmpty) 21 Text( 22 name, 23 style: const TextStyle( 24 color: Colors.grey, 25 fontSize: 12, 26 ), 27 ), 28 const SizedBox(height: 8), 29 SelectableText( 30 code, 31 style: const TextStyle( 32 fontFamily: 'monospace', 33 color: Colors.greenAccent, 34 fontSize: 13, 35 height: 1.5, 36 ), 37 ), 38 ], 39 ), 40 ); 41 }, 42)

Streaming-aware rendering

When an LLM streams output, the closing ``` fence may not have arrived yet. The closed parameter lets you show a different UI while the code block is still being written.

streaming_code.dart
1// The 'closed' parameter tells you whether the code fence is complete. 2// Use it to show a placeholder while the model is still streaming. 3codeBuilder: (context, name, code, closed) { 4 if (!closed) { 5 return Container( 6 padding: const EdgeInsets.all(12), 7 decoration: BoxDecoration( 8 color: Colors.grey.shade900, 9 borderRadius: BorderRadius.circular(8), 10 ), 11 child: Text( 12 code, 13 style: const TextStyle(fontFamily: 'monospace', color: Colors.white70), 14 ), 15 ); 16 } 17 // Full renderer once complete 18 return MyHighlightedCodeBlock(language: name, code: code); 19}