패키지, 저장소 및 앱 카테고리 검색

code_text_field 표지
패키지 상세v1.1.0

code_text_field

구문 강조, 양방향 스크롤링 및 코드 수정자를 지원하는 사용자 정의 가능한 코드 필드

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
1.6만
좋아요
171
Pub 점수
150

패키지 설치

flutter pub add code_text_field

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Flutter용 사용자 정의 가능한 코드 텍스트 필드로, 구문 강조, 양방향 스크롤 및 코드 수정자 지원을 제공합니다. 앱 내에서 가볍지만 강력한 코드 편집 경험을 필요로 하는 개발자를 위한 것입니다. Android, iOS, Web, macOS, Windows, Linux 등 여러 플랫폼을 지원하여 크로스플랫폼 개발에 적합합니다. Flutter 위젯 시스템과 원활하게 통합되며, 코드의 외관과 동작에 대한 세밀한 제어가 가능합니다.

사용 사례

  • 개발자 도구에서 인라인 코드 편집
  • 교육용 앱에서 구문 강조 코드 입력
  • 실시간 코드 협업 인터페이스
  • 코드 스니펫 생성 및 표시
  • Flutter 앱에서 사용자 지정 IDE 유사 컴포넌트

주요 기능

  • 구문 강조
  • 양방향 스크롤
  • 코드 수정자 지원
  • 크로스 플랫폼 호환성
  • 사용자 지정 스타일
  • 경량 통합

적합한 대상

  • Flutter 개발자가 코드 편집기 구축 중
  • 프로그래밍을 가르치는 교육용 앱
  • 개발자 도구 및 IDE 확장 기능
  • 실시간 코드 입력이 필요한 앱
  • 다양한 플랫폼 간에 일관된 코드 UI가 필요한 팀

고려 사항

  • 고급 구문 규칙을 사용하려면 수동 설정이 필요합니다
  • 매우 큰 코드 파일에서는 성능이 달라질 수 있습니다
  • 제한된 내장 언어 지원(구성으로 확장 가능)
  • 복잡한 사용 사례의 경우 추가적인 상태 관리가 필요할 수 있습니다
  • 완전한 기능의 IDE 워크플로우를 위한 것이 아님

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

CodeField

A customizable code text field supporting syntax highlighting

Pub Website shields.io GitHub license Awesome Flutter

Live demo

A live demo showcasing a few language / theme combinations

Showcase

The experimental VM dlox uses CodeField in its online editor

Features

  • Code highlight for 189 built-in languages with 90 themes thanks to flutter_highlight
  • Easy language highlight customization through the use of theme maps
  • Fully customizable code field style through a TextField like API
  • Handles horizontal/vertical scrolling and vertical expansion
  • Supports code modifiers
  • Works on Android, iOS, Web, MacOS, Windows, and Linux

Code modifiers help manage indents automatically

The editor is wrapped in a horizontal scrollable container to handle long lines

Installing

In the pubspec.yaml of your flutter project, add the following dependency:

dependencies:
  ...
  code_text_field: <latest_version>

latest version

In your library add the following import:

import 'package:code_text_field/code_text_field.dart';

Simple example

A CodeField widget works with a CodeController which dynamically parses the text input according to a language and renders it with a theme map

import 'package:flutter/material.dart';
import 'package:code_text_field/code_text_field.dart';
// Import the language & theme
import 'package:highlight/languages/dart.dart';
import 'package:flutter_highlight/themes/monokai-sublime.dart';

class CodeEditor extends StatefulWidget {
  @override
  _CodeEditorState createState() => _CodeEditorState();
}

class _CodeEditorState extends State<CodeEditor> {
  CodeController? _codeController;

  @override
  void initState() {
    super.initState();
    final source = "void main() {\n    print(\"Hello, world!\");\n}";
    // Instantiate the CodeController
    _codeController = CodeController(
      text: source,
      language: dart,
    );
  }

  @override
  void dispose() {
    _codeController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CodeTheme(
      data: const CodeThemeData(styles: monokaiSublimeTheme),
      child: CodeField(
        controller: _codeController!,
        textStyle: const TextStyle(fontFamily: 'SourceCode'),
      ),
    );
  }
}

Here, the monospace font Source Code Pro has been added to the assets folder and to the pubspec.yaml file.

Parser options

On top of a language definition, word-wise styling can be specified in the stringMap field

_codeController = CodeController(
  //...
  stringMap: {
    "Hello": TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
    "world": TextStyle(fontStyle: FontStyle.italic, color: Colors.green),
  },
);

More complex regexes may also be used with the patternMap. When a language is used though, its regexes patterns take precedence over patternMap and stringMap.

_codeController = CodeController(
  //...
  patternMap: {
    r"\B#[a-zA-Z0-9]+\b":
        TextStyle(fontWeight: FontWeight.bold, color: Colors.purpleAccent),
  },
);

Both patternMap and stringMap can be used without specifying a language.

_codeController = CodeController(
  text: source,
  patternMap: {
    r'".*"': TextStyle(color: Colors.yellow),
    r'[a-zA-Z0-9]+\(.*\)': TextStyle(color: Colors.green),
  },
  stringMap: {
    "void": TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
    "print": TextStyle(fontWeight: FontWeight.bold, color: Colors.blue),
  },
);

Code Modifiers

Code modifiers can be created to react to special keystrokes. The default modifiers handle tab to space & automatic indentation. Here's the implementation of the default TabModifier

class TabModifier extends CodeModifier {
  const TabModifier() : super('\t');

  @override
  TextEditingValue? updateString(
      String text, TextSelection sel, EditorParams params) {
    final tmp = replace(text, sel.start, sel.end, " " * params.tabSpaces);
    return tmp;
  }
}

API

CodeField
const CodeField({
    Key? key,
    required this.controller,
    this.minLines,
    this.maxLines,
    this.expands = false,
    this.wrap = false,
    this.background,
    this.decoration,
    this.textStyle,
    this.padding = EdgeInsets.zero,
    this.lineNumberStyle = const LineNumberStyle(),
    this.enabled,
    this.onTap,
    this.readOnly = false,
    this.cursorColor,
    this.textSelectionTheme,
    this.lineNumberBuilder,
    this.focusNode,
    this.onChanged,
    this.isDense = false,
    this.smartQuotesType,
    this.keyboardType,
    this.lineNumbers = true,
    this.horizontalScroll = true,
    this.selectionControls,
    this.hintText,
    this.hintStyle,
  })
LineNumberStyle
  const LineNumberStyle({
    this.width = 42.0,
    this.textAlign = TextAlign.right,
    this.margin = 10.0,
    this.textStyle,
    this.background,
  });
CodeController
CodeController({
    String? text,
    Mode? language,
    this.patternMap,
    this.stringMap,
    this.params = const EditorParams(),
    this.modifiers = const [
      IndentModifier(),
      CloseBlockModifier(),
      TabModifier(),
    ],
  }) 

Limitations

Notes

A breaking change to the TextEditingController was introduced in flutter beta, dev & master channels. The branch beta should comply with those changes.

카테고리

의존성

의존성 목록 3 개

소스 저장소

이 패키지를 사용하는 프로젝트