cosmic_frontmatter is a package that provides a simple way to parse the frontmatter of a markdown file.

Overview

cosmic_frontmatter

cosmic_frontmatter is a package that provides a simple way to parse the frontmatter of a markdown file.

Getting started

To get started, you need to install the package by adding cosmic_frontmatter to your pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter

  cosmic_frontmatter: ^1.0.1

Usage

cosmic_frontmatter exports a parseFrontmatter function that takes a string (your markdown document) and a builder function. The builder function is called with the parsed frontmatter as a map.

This allows you to get typed frontmatter. Here's an example that uses json_serializable and freezed to generate a MockFrontmatter class:

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);
}

With the MockFrontmatter in place, you can parse the frontmatter of a markdown file:

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);
});

This can then be used in your app however you want. Here's an example which merely displays the frontmatter on the screen, along-side the markdown body:

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 is a widget that displays markdown. It comes from the flutter_markdown package. You can find more information about it here.

You might also like...

Create a simple way to keep track of weekly expenses with flutter

Create a simple way to keep track of weekly expenses with flutter

Expenses app The purpose of this app is to create a simple way to keep track of weekly expenses UI Getting Started This project is a starting point fo

Jul 26, 2022

Provide easy and flexible way to show SnackBar. Simple text, undo, and error style are supported.

Provide easy and flexible way to show SnackBar. Simple text, undo, and error style are supported.

snack_bar_presenter Provide easy and flexible way to show SnackBar. Simple text, undo, and error style are supported. . . . Usage import 'package:exam

Nov 30, 2020

This plugin lets you show a message in a simple way.

error_message This plugin lets you show a message in a simple way. Usage ErrorMessage( icon: Icon(Icons.error), title: "Error Title",

Dec 5, 2021

Simple way to manage database.

database_manager (Developer Preview) Simple way to manage database. Version control and application's database schema. Simplify CRUD operations. Insta

Jul 14, 2021

An Advanced Logging Framework develop in flutter that provides quick & simple logging solution.

An Advanced Logging Framework develop in flutter that provides quick & simple logging solution.

FLogs Advance Logging Framework FLog is an Advanced Logging Framework develop in flutter that provides quick & simple logging solution. All logs are s

Dec 30, 2022

Create mobile file manager design using Flutter

Create mobile file manager design using Flutter

Mobile File Manager Watch it on YouTube Home & Cloud Screen On this file manager design has two pages. The Home page displays file usage information,

Dec 23, 2022

Experiment for building file system.

experiment_file_system A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you s

Nov 15, 2021

Generate a new file by compressed video, and provide metadata. Get video thumbnail from a video path, supports JPEG/GIF. To reduce app size not using FFmpeg in IOS.

Generate a new file by compressed video, and provide metadata. Get video thumbnail from a video path, supports JPEG/GIF. To reduce app size not using FFmpeg in IOS.

flutter_video_compress Generate a new path by compressed video, Choose to keep the source video or delete it by a parameter. Get video thumbnail from

Dec 8, 2022

Automatically increment File & Directory name and create

Name Plus Automatically increment File & Directory name and create. Getting Started In the pubspec.yaml of your flutter project, add the following dep

Dec 29, 2021
Comments
  • Example for nested frontmatter

    Example for nested frontmatter

    Hey @PaulHalliday , thanks for the amazing library. Great job!

    How to serialize nested frontmatter, with freezed?

    I tried to do as discussed here with no luck: https://github.com/rrousselGit/freezed/issues/86#issuecomment-957956629

    Error I get is : type 'YamlMap' is not a subtype of type 'Map<String, dynamic>' in type cast,

    An example how to serialize and access nested frontmatter would be a huge help!

    I am trying to parse a frontmatter like this, place is being returned as YamlMap instead of Map<String,dynamic>

    ---
    name: "foobar"
    date: 1990-09-01
    place:
      birth: "London"
      death: "Paris"
    ---
    
    opened by mkhnpr 0
Owner
cosmic.horse
Creative web/app development in Sunderland, United Kingdom.
cosmic.horse
A simple note-taking app with a markdown editor, built with Flutter and Firebase

Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is your first Flutter project:

Dev-Salem 150 Dec 25, 2022
Convert quill (Delta) fromat to and from markdown

Limitation Image Currently this convertor doesn't support image alts, only image src will be retained Block attributes exclusivity flutter_quill block

Tarekk Mohamed Abdalla 6 May 20, 2022
Convert quill (Delta) fromat to and from markdown

Markdown Quill ⚠️ [Please note this package is under development the API might change]. Provides converters to convert from markdown to quill (Delta)

Tarekk Mohamed Abdalla 6 May 20, 2022
A Markdown-based note-taking app for mobile devices.

Noteless A markdown-based note-taking app for Android Compatible with notes saved in Notable Features Markdown-optimized editor with syntax highlighti

null 460 Dec 31, 2022
Recipe-flavored markdown: make recipes easy to create and maintain

Recipe-Flavored Markdown Have you ever wanted a simpler approach to writing and

Joanna May 28 Dec 8, 2022
Android app that converts an URL to markdown, and lets you share it to your favorite notes app.

markdownr Android app that converts an URL to markdown, and lets you share it to your favorite notes app. I've written this app to save articles I fou

Andrea Ghensi 41 Dec 10, 2022
Munem Sarker 1 Jan 25, 2022
The FlexGrid control provides a powerful and quickly way to display data in a tabular format. It is including that frozened column/row,loading more, high performance and better experience in TabBarView/PageView.

flex_grid Language: English| 中文简体 The FlexGrid control provides a powerful and quickly way to display data in a tabular format. It is including that f

FlutterCandies 39 Nov 8, 2022
small package to generate code in a simple way

PART OF QUEEN PACKAGES ?? Dart File Builder Motivation generating dart code with build_runner will not work if you are trying to convert json to dart

FlutterQueen 3 Sep 24, 2022
Petit httpd - This is a simple HTTP file server integrated with Let's Encrypt, gzip and CORS

Petit httpd - This is a simple HTTP file server integrated with Let's Encrypt, gzip and CORS

Graciliano Monteiro Passos 4 Nov 24, 2022