Flutter Code Editor

repository·main·Indexed 43 days ago

https://github.com/akvelon/flutter-code-editor

A multi-platform code editor widget for Flutter featuring syntax highlighting, code folding, autocompletion, and code analysis. It provides a high-level CodeField widget with a gutter and line numbers, as well as a CodeController for managing state, dynamic language switching, and programmatic text manipulation. Supports named sections for read-only or hidden code blocks and integrates with the highlight package for theme and language configuration.

Tokens
9.1K
Snippets
34
Records
41
Agent score
54%

What's inside Flutter Code Editor

  1. Use Named Sections for Manipulation

    main

    Named sections allow you to target specific parts of the code.

    1. Define in code: Use comments like // [START section_name] and // [END section_name].
    2. Parse in controller: Pass a parser like BracketsStartEndNamedSectionParser to the CodeController.

    Sections can be used to make specific parts of the code read-only or to hide everything except that section.

    final text = '''
    class MyClass {
        // [START section1]
        void myMethod() {}
        // [END section1]
    }
    ''';
    
    final controller = CodeController(
      text: text,
      language: java,
      namedSectionParser: const BracketsStartEndNamedSectionParser(),
    );
  2. Access Text via CodeController

    main

    The CodeController extends TextEditingController, but its properties behave differently when code is folded:

    • text: Returns/sets the visible text (excludes folded blocks).
    • value: Returns/sets the TextEditingValue of the visible text.
    • fullText: Returns/sets the entire text, including folded blocks and hidden service comments.
  3. Migrate from version 0.1 to 0.2

    main

    When upgrading from version 0.1 to 0.2 of flutter-code-editor, apply the following breaking changes:

    1. Text Access: Replace the use of rawText with text.
    2. CodeController Configuration: Remove the webSpaceFix parameter from the CodeController constructor.
    3. Indentation API: Rename IntendModifier to IndentModifier.
  4. Apply Pre-defined and Custom Themes

    main

    Themes are applied using the CodeTheme widget.

    Pre-defined Themes: Use themes from the flutter_highlight package by passing them to CodeThemeData(styles: ...).

    Custom Themes: Create a map of styles following the structure of existing themes in flutter_highlight.

    CodeTheme(
      data: CodeThemeData(styles: monokaiSublimeTheme),
      child: CodeField(controller: controller),
    )
  5. Basic Usage of Flutter Code Editor

    main

    To use the editor, initialize a CodeController with your initial text and language, then wrap a CodeField widget inside a CodeTheme widget to provide syntax highlighting styles. The CodeController manages the state and content of the editor.

    import 'package:flutter/material.dart';
    import 'package:flutter_code_editor/flutter_code_editor.dart';
    import 'package:flutter_highlight/themes/monokai-sublime.dart';
    import 'package:highlight/languages/java.dart';
    
    final controller = CodeController(
      text: '...', // Initial code
      language: java,
    );
    
    // In your widget tree:
    CodeTheme(
      data: CodeThemeData(styles: monokaiSublimeTheme),
      child: CodeField(
        controller: controller,
      ),
    )
  6. Configure Syntax Highlighting and Languages

    main

    Syntax highlighting is powered by the highlight package. You select a language by passing a language variable (e.g., python, java, go) to the CodeController. You can change the language dynamically using controller.setLanguage().

    import 'package:highlight/languages/python.dart';
    
    // Set language on initialization
    final controller = CodeController(
      text: '...', 
      language: python,
    );
    
    // Change language dynamically
    controller.setLanguage(go, DefaultLocalAnalyzer());
  7. Migrate from code_text_field to flutter-code-editor 0.1

    main

    If you are migrating from the code_text_field package to flutter-code-editor (v0.1 and later), follow these steps to ensure compatibility and avoid UI bugs:

    1. Update Dependencies: Replace the code_text_field package with flutter_code_editor in your pubspec.yaml.
    2. Fix Layout Issues: Do not use the CodeField.expands property. Using expands causes the code to scroll while the line numbers remain frozen. Instead, wrap the entire editor widget in an Expanded widget to handle layout.
    3. Update Theme Implementation: Instead of passing a theme directly to the CodeController, use the CodeTheme widget to provide the theme to the editor.
    // Instead of:
    // CodeController(theme: myTheme)
    
    // Use:
    CodeTheme(
      data: myTheme,
      child: CodeField(
        controller: myController,
      ),
    )
  8. Use HiddenRanges to manage collapsed code regions

    main

    The HiddenRanges class is a data structure used to manage ranges of code that are hidden from view (e.g., during code folding). It provides utilities to translate between positions and selections in the full, original text and the visible, "cut" text.

    Key capabilities include:

    • String Manipulation: Removing hidden content from strings using cutString or removing it from syntax-highlighted results using cutHighlighted.
    • Position Translation: Converting a position from the full text to the visible text via cutPosition, or recovering the full-text position from a visible position via recoverPosition.
    • Selection Translation: Converting TextSelection objects between full-text and visible-text coordinate systems using cutSelection and recoverSelection.
    • Search Result Mapping: Adjusting SearchResult match offsets to match the visible text using cutSearchResult.

    Note: When using recoverPosition, you must specify a TextAffinity (upstream or downstream) to determine where the cursor should land if it is placed exactly at a collapsed range boundary.

    /// Example of translating a selection from full text to visible text
    TextSelection visibleSelection = hiddenRanges.cutSelection(fullTextSelection);
  9. Change language and theme dynamically

    main

    You can update the syntax highlighting and visual style of the editor at runtime by modifying the language and theme properties provided to the controller or widget. This allows users to switch between different programming languages or visual modes (e.g., Light vs Dark) while editing.

    // Example pattern for dynamic updates:
    // Update the language and theme properties to change the editor's appearance.
  10. Use the CodeField widget for advanced editor features

    main

    The CodeField widget is the primary high-level component for a full editor experience. It automatically includes:

    • A gutter (for line numbers and markers)
    • Code folding capabilities
    • Basic autocompletion support
    // Use the CodeField widget to enable gutter, folding, and autocompletion.
    CodeField(
      controller: controller,
      // ... other properties
    )
  11. Implement a minimal code editor using CodeController and TextField

    main

    For a lightweight implementation, you can use a CodeController in conjunction with a standard Flutter TextField. This approach provides the core logic for code handling without the full UI features of the CodeField widget.

    // Refer to the minimal implementation pattern:
    // Use CodeController with an ordinary TextField.