How to Render Markdown (MD) String in Flutter

In this example, we are going to show MarkDown (MD) text as a widget in Flutter App. You will learn to render or convert MD strings to Flutter widgets. We will use flutter_markdown package to convert MarkDown text to the widget.

First, you need to add flutter_markdown package in your project by adding the following lines in pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  flutter_markdown: ^0.6.9

Now import the package to your script: 

import 'package:flutter_markdown/flutter_markdown.dart';

Now show the markdown like below in your widget tree:

String mdstring = """ 
Markdown is the **best**!

* It has lists.
* It has [links - FlutterCampus.com](https://www.fluttercampus.com).
* It has _so much more_...
""";
Markdown(
    data:mdstring
)

Markdown has its own scrolling, margin, and padding, you can use MarkdownBody() widget to show Markdown without any scrolling and padding.

MarkdownBody(
    data:mdstring
)

You can also convert Markdown to HTML using markdown package and later convert HTML to the Flutter widget.

To make the rendered text selectable, you can use Markdown() widget like below:

Markdown(
    selectable: true,
    data: mdstring
);

import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';

Future<void> main() async {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {

  String mdstring = """ 
Markdown is the **best**!

* It has lists.
* It has [links - FlutterCampus.com](https://www.fluttercampus.com).
* It has _so much more_...
    """;
    
    return  Scaffold(
          appBar: AppBar( 
              title: Text("MarkDown in Flutter"),
              backgroundColor: Colors.redAccent,
          ),
          body: Container( 
            child: Markdown(
                 data:mdstring
              ) 
          ),
           
       );
  }
}

Here, we have Markdown string and we have rendered the MD string to the widget using Markdown() widget from flutter_markdown package.

In this way, you can render Markdown (MD) string to Flutter widgets. 

No any Comments on this Article


Please Wait...