Flutter代码查看插件universal_code_viewer的使用
Flutter代码查看插件universal_code_viewer的使用
universal_code_viewer
是一个功能强大且可定制的 Flutter 代码查看器,支持超过50种编程语言和多种主题。以下是该插件的详细使用说明。
特性
- 🎨 多个内置主题(如 VSCode、GitHub、Dracula 等)
- 🔍 自动检测语言
- 📝 支持50多种编程语言
- ✨ 可自定义语法样式
- 📋 复制到剪贴板的功能
- 🔢 可选行号
- 🎯 专为 Flutter 构建
平台支持
Android | iOS | Web | macOS | Linux | Windows |
---|---|---|---|---|---|
✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
预览
移动端 (iOS)
Light Theme | Dark Theme |
---|---|
![]() |
![]() |
移动端 (Android)
Light Theme | Dark Theme |
---|---|
![]() |
![]() |
Web
Light Theme | Dark Theme |
---|---|
![]() |
![]() |
安装
在 pubspec.yaml
文件中添加以下依赖:
dependencies:
universal_code_viewer: ^1.0.0
然后运行以下命令以安装包:
flutter pub get
基本用法
import 'package:universal_code_viewer/universal_code_viewer.dart';
UniversalCodeViewer(
code: '''
void main() {
print("Hello, World!");
}
''',
style: SyntaxHighlighterStyles.vscodeDark,
)
配置选项
参数 | 类型 | 默认值 | 描述 |
---|---|---|---|
code |
String |
必填 | 要高亮的源代码 |
style |
SyntaxStyle |
必填 | 语法高亮主题 |
showLineNumbers |
bool |
true |
显示/隐藏行号 |
codeLanguage |
String |
NA | 有时自动检测语言可能不工作时显示此文本 |
isCodeLanguageView |
bool |
NA | 启用/禁用自动检测语言文本 |
copyWidget |
Widget |
NA | 包含自定义的 copyWidget |
enableCopy |
bool |
true |
启用/禁用复制按钮 |
padding |
EdgeInsetsGeometry? |
EdgeInsets.all(16) |
自定义填充 |
支持的语言
编程语言
- Ada
- Assembly
- AWK
- Bash/Shell
- C
- C++
- C#
- Clojure
- COBOL
- D
- Dart
- Elixir
- Elm
- Erlang
- F#
- Fortran
- Go
- Groovy
- Haskell
- Java
- JavaScript
- Julia
- Kotlin
- Lisp
- Lua
- MATLAB
- Objective-C
- Pascal
- Perl
- PHP
- Prolog
- Python
- R
- Ruby
- Rust
- Scala
- Scheme
- Simula
- Smalltalk
- Swift
- TCL
- TypeScript
- VB.NET
- VHDL
- Verilog
Web 技术
- CSS
- HTML
- LESS
- SCSS
- SASS
数据库
- PL/SQL
- SQL
框架
- Angular
- Django
- Express.js
- Flask
- Node.js
- React
- Vue.js
内置主题
// 可用的主题
SyntaxHighlighterStyles.vscodeLight
SyntaxHighlighterStyles.vscodeDark // 默认
SyntaxHighlighterStyles.githubLight
SyntaxHighlighterStyles.githubDark
SyntaxHighlighterStyles.atomOneLight
SyntaxHighlighterStyles.monokaiPro
SyntaxHighlighterStyles.duotoneDarkSea
SyntaxHighlighterStyles.vue
SyntaxHighlighterStyles.ayuDark
SyntaxHighlighterStyles.draculaTheme
主题示例
VSCode Dark (默认)
static const vscodeDark = SyntaxStyle(
baseStyle: TextStyle(color: Colors.white70),
keywordStyle: TextStyle(color: Color(0xFF569CD6)),
classStyle: TextStyle(color: Color(0xFF4EC9B0)),
methodStyle: TextStyle(color: Color(0xFFDCDCAA)),
variableStyle: TextStyle(color: Color(0xFF9CDCFE)),
stringStyle: TextStyle(color: Color(0xFFCE9178)),
numberStyle: TextStyle(color: Color(0xFFB5CEA8)),
commentStyle: TextStyle(color: Color(0xFF6A9955)),
tagStyle: TextStyle(color: Color(0xFF569CD6)),
attributeStyle: TextStyle(color: Color(0xFF9CDCFE)),
backgroundColor: Color(0xFF1E1E1E),
);
GitHub Light
static const githubLight = SyntaxStyle(
baseStyle: TextStyle(color: Color(0xFF24292E)),
keywordStyle: TextStyle(color: Color(0xFFd73a49)),
classStyle: TextStyle(color: Color(0xFF6f42c1)),
methodStyle: TextStyle(color: Color(0xFF6f42c1)),
variableStyle: TextStyle(color: Color(0xFF005cc5)),
stringStyle: TextStyle(color: Color(0xFF032f62)),
numberStyle: TextStyle(color: Color(0xFF005cc5)),
commentStyle: TextStyle(color: Color(0xFF6a737d)),
tagStyle: TextStyle(color: Color(0xFF22863a)),
attributeStyle: TextStyle(color: Color(0xFF6f42c1)),
backgroundColor: Colors.white,
);
高级用法
自定义主题创建
final myCustomTheme = SyntaxStyle(
baseStyle: TextStyle(fontSize: 14.0, color: Colors.grey[800]),
keywordStyle: TextStyle(fontSize: 14.0, color: Colors.blue[800]),
classStyle: TextStyle(fontSize: 14.0, color: Colors.purple[800]),
methodStyle: TextStyle(fontSize: 14.0, color: Colors.indigo[800]),
variableStyle: TextStyle(fontSize: 14.0, color: Colors.teal[800]),
stringStyle: TextStyle(fontSize: 14.0, color: Colors.green[800]),
numberStyle: TextStyle(fontSize: 14.0, color: Colors.orange[800]),
commentStyle: TextStyle(fontSize: 14.0, color: Colors.grey[600]),
tagStyle: TextStyle(fontSize: 14.0, color: Colors.red[800]),
attributeStyle: TextStyle(fontSize: 14.0, color: Colors.purple[800]),
operatorStyle: TextStyle(fontSize: 14.0, color: Colors.grey[800]),
punctuationStyle: TextStyle(fontSize: 14.0, color: Colors.grey[800]),
backgroundColor: Colors.grey[100]!,
);
语言示例
Python
UniversalCodeViewer(
code: '''
def fibonacci(n):
"""Generate Fibonacci sequence"""
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
''',
style: SyntaxHighlighterStyles.vscodeDark,
codeLanguage: 'Python'
);
JavaScript
UniversalCodeViewer(
code: '''
class Calculator {
constructor() {
this.result = 0;
}
add(num) {
this.result += num;
return this;
}
getResult() {
return this.result;
}
}
''',
style: SyntaxHighlighterStyles.githubLight,
codeLanguage: 'JavaScript'
);
HTML
UniversalCodeViewer(
code: '''
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
<style>
.container {
margin: 20px;
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<h1>Welcome</h1>
<p>This is a sample page.</p>
</div>
</body>
</html>
''',
style: SyntaxHighlighterStyles.monokaiPro,
codeLanguage: 'HTML'
);
示例1:使用自定义字体族与 VSCode Dark 主题
final vscodeDarkWithCustomFont = SyntaxHighlighterStyles.vscodeDark
.withFontFamily('Fira Code')
.withFontSize(16.0);
示例2:使用不同的字体与 GitHub Light 主题
final githubLightWithCustomFont = SyntaxHighlighterStyles.githubLight
.withFontFamily('JetBrains Mono')
.withFontSize(14.0);
示例3:结合多个字体和大小与 Dracula 主题
final draculaCustomized = SyntaxHighlighterStyles.draculaTheme
.withFontFamily('Cascadia Code')
.withFontSize(15.0);
示例4:自定义样式与不同元素的不同字体
final customStyle = SyntaxStyle(
baseStyle: const TextStyle(
fontSize: 14.0,
color: Color(0xFF24292E),
fontFamily: 'Source Code Pro',
),
keywordStyle: const TextStyle(
fontSize: 14.0,
color: Color(0xFFD73A49),
fontFamily: 'Fira Code',
fontWeight: FontWeight.bold,
),
classStyle: const TextStyle(
fontSize: 14.0,
color: Color(0xFF6F42C1),
fontFamily: 'JetBrains Mono',
),
methodStyle: const TextStyle(
fontSize: 14.0,
color: Color(0xFF6F42C1),
fontFamily: 'Cascadia Code',
),
stringStyle: const TextStyle(
fontSize: 14.0,
color: Color(0xFF032F62),
fontFamily: 'Fira Code',
fontStyle: FontStyle.italic,
),
numberStyle: const TextStyle(
fontSize: 14.0,
color: Color(0xFF005CC5),
fontFamily: 'JetBrains Mono',
),
commentStyle: const TextStyle(
fontSize: 14.0,
color: Color(0xFF6A737D),
fontFamily: 'Source Code Pro',
fontStyle: FontStyle.italic,
),
backgroundColor: Colors.white,
// ... 其他样式属性
).withFontSize(16.0); // 增加所有字体大小
示例代码
import 'package:flutter/material.dart';
import 'package:universal_code_viewer/universal_code_viewer.dart';
void main() {
runApp(const SyntaxHighlighterDemo());
}
class SyntaxHighlighterDemo extends StatelessWidget {
const SyntaxHighlighterDemo({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Universal Code Viewer',
theme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.light,
),
darkTheme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.dark,
),
home: const ExampleScreen(),
);
}
}
class ExampleScreen extends StatefulWidget {
const ExampleScreen({super.key});
[@override](/user/override)
State<ExampleScreen> createState() => _ExampleScreenState();
}
class _ExampleScreenState extends State<ExampleScreen> {
final Map<String, String> codeExamples = {
'Dart': '''
void main() {
// Example of a Dart class
final calculator = Calculator();
print(calculator.add(5).multiply(2).result); // Outputs: 10
}
class Calculator {
double result = 0;
Calculator add(double value) {
result += value;
return this;
}
Calculator multiply(double value) {
result *= value;
return this;
}
}
''',
'Python': '''
def fibonacci(n: int) -> list[int]:
"""Generate Fibonacci sequence up to n"""
sequence = [0, 1]
while sequence[-1] <= n:
sequence.append(sequence[-1] + sequence[-2])
return sequence[:-1]
# Example usage with type hints
def calculate_stats(numbers: list[int]) -> dict[str, float]:
"""Calculate basic statistics for a list of numbers"""
return {
"mean": sum(numbers) / len(numbers),
"min": min(numbers),
"max": max(numbers)
}
# Test the functions
if __name__ == "__main__":
fib_sequence = fibonacci(100)
stats = calculate_stats(fib_sequence)
print(f"Statistics: {stats}")
''',
'JavaScript': '''
// Modern JavaScript example with ES6+ features
class DataProcessor {
constructor(data) {
this.data = data;
}
async processData() {
try {
// Using modern JS features
const results = await Promise.all(
this.data.map(async (item) => {
const processed = await this.transform(item);
return {
...processed,
timestamp: new Date().toISOString()
};
})
);
return results.filter(item => item.value > 0)
.sort((a, b) => b.value - a.value);
} catch (error) {
console.error(`Processing failed: ${error}`);
throw error;
}
}
async transform(item) {
// Simulate async processing
return new Promise(resolve => {
setTimeout(() => {
resolve({
id: item.id,
value: item.data * 2
});
}, 100);
});
}
}
''',
'HTML': '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modern HTML Example</title>
<style>
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
padding: 20px;
}
.card {
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
padding: 20px;
}
</style>
</head>
<body>
<div class="container">
<article class="card">
<header>
<h2>Modern HTML Features</h2>
</header>
<main>
<p>Examples of modern HTML5 elements and attributes:</p>
<details>
<summary>Click to expand</summary>
<ul>
<li>Semantic HTML5 elements</li>
<li>Modern attributes</li>
<li>Grid layout</li>
</ul>
</details>
</main>
<footer>
<small>Last updated: 2024</small>
</footer>
</article>
</div>
</body>
</html>
''',
};
String currentLanguage = 'Dart';
SyntaxStyle currentTheme = SyntaxHighlighterStyles.vscodeDark;
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Universal Code Viewer'),
actions: [
IconButton(
icon: const Icon(Icons.color_lens),
onPressed: _showThemeSelector,
),
],
),
body: Column(
children: [
_buildLanguageSelector(),
Expanded(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: UniversalCodeViewer(
code: codeExamples[currentLanguage]!,
style: currentTheme,
codeLanguage: currentLanguage.toUpperCase(),
),
),
),
),
],
),
);
}
Widget _buildLanguageSelector() {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
child: Row(
children: codeExamples.keys.map((language) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: ChoiceChip(
label: Text(language),
selected: currentLanguage == language,
onSelected: (selected) {
if (selected) {
setState(() => currentLanguage = language);
}
},
),
);
}).toList(),
),
);
}
void _showThemeSelector() {
showModalBottomSheet(
context: context,
builder: (context) {
return SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
title: const Text('VSCode Dark'),
onTap: () => _updateTheme(SyntaxHighlighterStyles.vscodeDark),
),
ListTile(
title: const Text('VSCode Light'),
onTap: () => _updateTheme(SyntaxHighlighterStyles.vscodeLight),
),
ListTile(
title: const Text('GitHub Dark'),
onTap: () => _updateTheme(SyntaxHighlighterStyles.githubDark),
),
ListTile(
title: const Text('GitHub Light'),
onTap: () => _updateTheme(SyntaxHighlighterStyles.githubLight),
),
ListTile(
title: const Text('Monokai Pro'),
onTap: () => _updateTheme(SyntaxHighlighterStyles.monokaiPro),
),
ListTile(
title: const Text('Dracula'),
onTap: () => _updateTheme(SyntaxHighlighterStyles.draculaTheme),
),
],
),
);
},
);
}
void _updateTheme(SyntaxStyle newTheme) {
setState(() => currentTheme = newTheme);
Navigator.pop(context);
}
}
// 示例页面展示多个高亮器
class MultipleHighlightersExample extends StatelessWidget {
const MultipleHighlightersExample({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Multiple Highlighters')),
body: const SingleChildScrollView(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Python with VSCode Dark:'),
UniversalCodeViewer(
code: '''
def greet(name: str) -> str:
return f"Hello, {name}!"
''',
style: SyntaxHighlighterStyles.vscodeDark,
),
SizedBox(height: 20),
Text('JavaScript with GitHub Light:'),
UniversalCodeViewer(
code: '''
function calculateTotal(items) {
return items
.filter(item => item.inStock)
.reduce((sum, item) => sum + item.price, 0);
}
''',
style: SyntaxHighlighterStyles.githubLight,
),
SizedBox(height: 20),
Text('HTML with Monokai Pro:'),
UniversalCodeViewer(
code: '''
<div class="card">
<h2>Hello World</h2>
<p>This is a sample card.</p>
</div>
''',
style: SyntaxHighlighterStyles.monokaiPro,
),
],
),
),
);
}
}
更多关于Flutter代码查看插件universal_code_viewer的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter代码查看插件universal_code_viewer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中使用universal_code_viewer
插件的示例代码。universal_code_viewer
是一个强大的插件,用于在Flutter应用中显示和格式化代码。
1. 添加依赖
首先,你需要在pubspec.yaml
文件中添加universal_code_viewer
的依赖:
dependencies:
flutter:
sdk: flutter
universal_code_viewer: ^1.0.0 # 请检查最新版本号
然后运行flutter pub get
来获取依赖。
2. 使用UniversalCodeViewer
组件
接下来,你可以在你的Flutter应用中使用UniversalCodeViewer
组件来显示代码。以下是一个完整的示例代码:
import 'package:flutter/material.dart';
import 'package:universal_code_viewer/universal_code_viewer.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Code Viewer Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CodeViewerScreen(),
);
}
}
class CodeViewerScreen extends StatelessWidget {
final String code = '''
void main() {
print('Hello, World!');
}
''';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Code Viewer Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: UniversalCodeViewer(
code,
language: 'dart', // 指定代码语言,支持多种语言
theme: CodeViewerThemeData(
// 可选:自定义主题
backgroundColor: Colors.grey[200]!,
textStyle: TextStyle(
fontFamily: 'Courier New',
fontSize: 14,
),
),
),
),
);
}
}
3. 运行应用
将上述代码保存到一个Flutter项目中,然后运行flutter run
来启动应用。你应该会看到一个包含格式化代码的页面。
4. 可选:自定义和扩展
universal_code_viewer
插件提供了多种自定义选项,比如设置高亮主题、调整字体大小、设置行号等。你可以查阅官方文档(假设文档存在并详细)来获取更多信息和高级用法。
注意事项
- 确保你使用的
universal_code_viewer
版本与Flutter SDK兼容。 - 插件可能会定期更新,因此建议定期查看最新的文档和更新日志。
希望这个示例能帮助你顺利地在Flutter项目中使用universal_code_viewer
插件来显示和格式化代码。