Skip to content
Talk to an engineerRequest access

CodeView

Show syntax-highlighted code in Flutter, with line numbers, highlighted lines, a header, tappable tokens, language detection and lazy rendering of long files.

A Dart StatelessWidget in CodeView with the default light theme

import 'package:val_highlight/languages/dart.dart';
import 'package:val_highlight_flutter/val_highlight_flutter.dart';
CodeView(source, language: dartLanguage)

Give it the source and a language; every other parameter is optional. With the defaults, the theme follows the app’s brightness, the code is selectable, long lines scroll sideways, and the code sits in 16 pixels of the theme’s background colour.

Kotlin with line numbers starting at 12, and lines 14 to 16 highlighted

firstLineNumber sets the number of the first line, for an excerpt of a longer file, and highlightedLines takes the numbers as shown in the gutter. Without highlightColor, highlighted lines get a translucent band: black at 8% opacity in a light theme, white at 13% in a dark one. Line numbers are never selected, so copying the code never copies them.

To draw the gutter yourself, pass a gutterBuilder. It gets the line number as shown and whether that line is highlighted, and is only used while lineNumbers is on. Return a fixed-width widget so the rows stay aligned:

CodeView(
source,
language: dartLanguage,
lineNumbers: true,
gutterBuilder: (context, lineNumber, highlighted) => SizedBox(
width: 32,
child: Text(
'$lineNumber',
textAlign: TextAlign.right,
style: TextStyle(fontWeight: highlighted ? FontWeight.bold : null),
),
),
)

A YAML file in CodeView with a title bar reading pubspec.yaml and a copy button

header places any widget above the code, on the code’s background — a file name, a language label, a copy button. padding applies to the code below it; the example trims its top so the header sits close to the code.

A long Python line wrapped across three rows, with its line number on the first

wrap: true wraps long lines instead of scrolling them sideways. With line numbers or highlighted lines, wrapped code is laid out one row per line, so each number stays beside the first row of its line.

TypeScript in which every type name is underlined

spanBuilder builds the span of every token, for links, hover effects, tooltips or your own styling. style is the token’s themed style, or null for plain text. Keep text: token.text, or the code on screen changes.

To react to taps instead, pass onTokenTap. Whitespace is not tappable; if both are set, spanBuilder wins.

CodeView(
source,
language: dartLanguage,
onTokenTap: (token) {
if (token.scope == Scopes.type) openDefinition(token.text);
},
)

A CodeToken is one run of text with the same scopes, never crossing a line break. A whole comment is one token: // TODO: ship is a single comment token, so look inside token.text to find words within a comment or string.

A Python snippet, highlighted as Python although no language was given

language is optional. Without it, CodeView runs language detection over the candidates in detectLanguages. When that finds nothing — or detectLanguages is empty, the default — it uses fallbackLanguage, which is genericLanguage: comments, strings, numbers, common keywords, types, calls and operators, the things most languages share.

// No highlighting at all for code in an unknown language.
CodeView(snippet, fallbackLanguage: plainTextLanguage)

Detection is a guess. When you know the language, pass it.

Markdown whose bash and JSON code fences are each highlighted in their own language

HTML highlights <style> as CSS and <script> as JavaScript with no setup. Markdown highlights each fenced block in the language named on its fence, which it looks up in a registry: give CodeView a CodeHighlighter that has one. Without a registry, fenced code is shown in the plain code scope.

CodeView lays short code out as one block of text. When the code has more than virtualizeAbove lines (1,000 by default) and the view’s height is bounded — inside an Expanded or a SizedBox, say — it switches to a lazy list that builds only the rows on screen. Pass scrollController to control that list. In an unbounded height, such as a Column without Expanded or a ListView, the code is never laid out lazily.

Expanded(
child: CodeView(
largeSource,
language: dartLanguage,
lineNumbers: true,
virtualizeAbove: 500,
),
)

Code of 50,000 characters or more is highlighted in a background isolate while it shows as plain text; on the web, which has no isolates, it is highlighted on a later turn of the event loop instead. Results are cached by code and language — the 32 most recent, by default — so showing the same code again does not highlight it again.

Every CodeView uses CodeHighlighter.shared unless you pass highlighter. Create your own to change the isolate threshold or the cache size, or to give it a language registry for Markdown fences:

final highlighter = CodeHighlighter(
registry: allLanguagesRegistry(),
isolateThreshold: 100000,
cacheSize: 64,
);

A language is compiled the first time it is used. To do that before the first code appears, preload the languages you expect; each is compiled as an idle-priority task, one at a time:

CodeHighlighter.shared.preload([dartLanguage, kotlinLanguage, jsonLanguage]);

clearCache() empties the result cache.

theme picks a ValTheme for one view; without it, CodeView follows CodeTheme and the app’s brightness. textStyle is merged over the default code style — monospace at 14 pixels with a line height of 1.5 — for example to set a font family. See Themes.

Shows syntax-highlighted code.

CodeView(source, language: dartLanguage)

Everything else is optional. The theme follows the app’s brightness (see CodeTheme for app-wide defaults). Results are cached, and inputs above CodeHighlighter.isolateThreshold are highlighted in a background isolate while plain text is shown.

Short code renders as one text block. Code with more than virtualizeAbove lines, placed where its height is bounded, renders one row per line in a lazy list, so only visible lines are laid out.

const CodeView(
String code, {
Key? key,
Grammar? language,
List<Grammar> detectLanguages = const [],
Grammar fallbackLanguage = genericLanguage,
ValTheme? theme,
TextStyle? textStyle,
EdgeInsetsGeometry? padding,
bool? lineNumbers,
int firstLineNumber = 1,
Set<int> highlightedLines = const {},
Color? highlightColor,
bool wrap = false,
bool selectable = true,
CodeHighlighter? highlighter,
int virtualizeAbove = 1000,
CodeGutterBuilder? gutterBuilder,
CodeLineBuilder? lineBuilder,
Widget? header,
ScrollController? scrollController,
ValueChanged<CodeToken>? onTokenTap,
CodeSpanBuilder? spanBuilder,
})

Creates a code view.

Field Type Default Description
code String required Source code to show.
language Grammar? Language of code. When null, the language is detected among detectLanguages; if that fails, fallbackLanguage is used.
fallbackLanguage Grammar genericLanguage Language used when language is null and detection finds nothing. Defaults to genericLanguage, which highlights what most languages share. Use plainTextLanguage for no highlighting.
detectLanguages List<Grammar> const [] Candidates for detection when language is null.
theme ValTheme? Color theme. Defaults to CodeTheme or the built-in light/dark theme.
textStyle TextStyle? Text style merged over the default monospace style.
padding EdgeInsetsGeometry? Padding inside the background. Defaults to CodeTheme.padding, or 16 on every side.
lineNumbers bool? Whether to show line numbers. Defaults to CodeTheme.lineNumbers, or false.
firstLineNumber int 1 Number shown for the first line.
highlightedLines Set<int> const {} Line numbers (as shown in the gutter) to highlight.
highlightColor Color? Background for highlightedLines.
wrap bool false Whether long lines wrap. When false, code scrolls horizontally.
selectable bool true Whether the code can be selected and copied.
highlighter CodeHighlighter? Highlighter to use. Defaults to CodeHighlighter.shared.
virtualizeAbove int 1000 Line count above which rows are built lazily.
gutterBuilder CodeGutterBuilder? Custom gutter cells.
lineBuilder CodeLineBuilder? Custom rows. Setting this always renders one row per line.
header Widget? A widget shown above the code, such as a title or copy button.
scrollController ScrollController? Vertical scroll controller for the lazy list.
onTokenTap ValueChanged<CodeToken>? Called when a token is tapped, such as an identifier to jump to. Whitespace is not tappable.
spanBuilder CodeSpanBuilder? Builds each token’s span, for hover effects, links, tooltips or custom styling. Takes priority over onTokenTap.

One piece of highlighted code, as passed to CodeView.onTokenTap and CodeView.spanBuilder. Pieces never cross a line break.

const CodeToken({
required String text,
required int start,
required int end,
required int line,
required List<String> scopes,
})

Creates a token.

Field Type Default Description
text String required The token’s source text.
start int required Start offset in the code.
end int required End offset (exclusive) in the code.
line int required Zero-based line.
scopes List<String> required Scopes from the outermost to the innermost; empty for plain text.
Member Type Description
scope String? Innermost scope, or null for plain text.

Builds the gutter cell for lineNumber. Return a fixed-width widget so rows stay aligned.

typedef CodeGutterBuilder = Widget Function(
BuildContext context,
int lineNumber,
bool highlighted,
)

Wraps the row for zero-based line. child is the default row.

typedef CodeLineBuilder = Widget Function(
BuildContext context,
int line,
Widget child,
)

Builds the span for one token, replacing the default. style is the token’s themed style (null for plain text). Return a TextSpan with text: token.text so the text stays unchanged.

typedef CodeSpanBuilder = InlineSpan Function(
BuildContext context,
CodeToken token,
TextStyle? style,
)

Highlights code for widgets, with a result cache and background isolates for large inputs.

Widgets use CodeHighlighter.shared unless given another. Create your own to change the thresholds or to resolve Markdown code fences:

final highlighter = CodeHighlighter(registry: allLanguagesRegistry());
CodeHighlighter({
LanguageRegistry? registry,
int isolateThreshold = 50000,
int cacheSize = 32,
})

Creates a highlighter.

Field Type Default Description
registry LanguageRegistry? Resolves languages named inside code, such as Markdown fences.
isolateThreshold int 50000 Inputs with at least this many characters are highlighted in a background isolate by highlight. On the web, which has no isolates, they are highlighted on the next event-loop turn instead.
cacheSize int 32 Number of results kept in the cache.
Member Type Description
static shared CodeHighlighter The default highlighter used by widgets.
cached(String code, Grammar language) HighlightResult? Cached result for code in language, if any.
usesIsolate(String code) bool Whether highlight would use a background isolate for code.
highlightSync(String code, Grammar language) HighlightResult Highlights code on the current isolate.
highlight(String code, Grammar language) Future<HighlightResult> Highlights code, using a background isolate for large inputs.
preload(Iterable<Grammar> languages) Future<void> Compiles languages ahead of time, one per idle frame, so the first code shown in each language has no compile delay (about 1–3 ms per language otherwise).
clearCache() void Empties the cache.