How to store a markdown editor content as html tags in flutter?

8 min read

One way to store a markdown editor content as HTML tags in Flutter is to use the markdown package. Here are the steps:

  1. Add the markdown package dependency to your pubspec.yaml file:
dependencies:
  markdown: ^5.1.0
  1. Import the package in your Dart file:
import 'package:markdown/markdown.dart' as markdown;
  1. Convert the Markdown content to HTML using the markdown.toHtml() method:
String markdownContent = "# Hello World\n\nThis is some **bold** text.";
String htmlContent = markdown.markdownToHtml(markdownContent);
  1. Store the HTML content in a variable or database:
// Store in a variable
String storedHtml = htmlContent;

// Store in a database
Firestore.instance.collection('content').document('myDocument').setData({
  'html': htmlContent,
});
  1. Display the HTML content in a WebView or Html widget:
// In a WebView
WebView(
  initialUrl: 'about:blank',
  onWebViewCreated: (WebViewController controller) {
    controller.loadUrl(Uri.dataFromString(
      storedHtml,
      mimeType: 'text/html',
      encoding: Encoding.getByName('utf-8'),
    ).toString());
  },
);

// In an Html widget
Html(
  data: storedHtml,
);