cosmic_frontmatter
cosmic_frontmatter 是一个包,它提供了一种简单的方式来解析 markdown 文件的 frontmatter。
入门
要开始使用,您需要通过将 cosmic_frontmatter 添加到您的 pubspec.yaml 文件中来安装该包。
dependencies:
flutter:
sdk: flutter
cosmic_frontmatter: ^1.0.0
用法
cosmic_frontmatter 导出一个 parseFrontmatter 函数,该函数接受一个字符串(您的 markdown 文档)和一个 builder 函数。builder 函数会接收解析后的 frontmatter(作为 map)并被调用。
这允许您获得类型化的 frontmatter。下面是一个使用 json_serializable 和 freezed 来生成 MockFrontmatter 类的示例。
import 'package:freezed_annotation/freezed_annotation.dart';
part 'mock_frontmatter.freezed.dart';
part 'mock_frontmatter.g.dart';
@freezed
class MockFrontmatter with _$MockFrontmatter {
const factory MockFrontmatter({
required String title,
required String author,
required String excerpt,
required String category,
required String date,
}) = _MockFrontmatter;
const MockFrontmatter._();
factory MockFrontmatter.fromJson(Map<String, dynamic> json) => _$MockFrontmatterFromJson(json);
}
有了 MockFrontmatter,您就可以解析 markdown 文件的 frontmatter 了。
const mockDocument = """
---
title: This is a test document
author: paul-halliday
excerpt: Learn how to use Markdown with Flutter at developer.school
category: Flutter
date: "2021-10-25"
---
You can learn how to use Markdown with Flutter at [developer.school](https://developer.school/tutorials/how-to-display-markdown-in-flutter).
""";
final mockFrontmatter = parseFrontmatter(
content: mockDocument,
frontmatterBuilder: (map) {
// Do anything you want with the `map`:
return MockFrontmatter.fromJson(map);
});
然后,您可以根据需要在您的应用中使用它。下面是一个示例,它只是将 frontmatter 和 markdown 主体一起显示在屏幕上。
class _MyHomePageState extends State<MyHomePage> {
late Document<MockFrontmatter> document;
@override
void initState() {
super.initState();
document = parseFrontmatter(
content: mockDocument,
frontmatterBuilder: (map) => MockFrontmatter.fromJson(map),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(document.frontmatter.title),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Title'),
subtitle: Text(document.frontmatter.title),
),
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Author'),
subtitle: Text(document.frontmatter.author),
),
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Excerpt'),
subtitle: Text(document.frontmatter.excerpt),
),
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Category'),
subtitle: Text(document.frontmatter.category),
),
ListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Date'),
subtitle: Text(document.frontmatter.date),
),
Text(
'Content',
style: Theme.of(context).textTheme.headline6,
),
const SizedBox(
height: 10,
),
Expanded(
child: MarkdownBody(
data: document.body,
),
),
],
),
),
),
);
}
}
MarkdownBody 是一个显示 markdown 的小部件。它来自 flutter_markdown 包。您可以在 这里 找到更多关于它的信息。