Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display a markdown file in flutter app and use the reference links

I am trying to take a markdown file, contents.md, and then display that on a page in my app, but I want to be able to use the reference links that I have added that point to different files, chapter1.md, chapter2.md, chapter3.md, and so on. I have been able to display markdown formatted from contents.md, but the links don't work.

Widget build(BuildContext context) {
    return Scaffold(appBar: AppBar(title: Text("Flutter Markdown"),),
      body: FutureBuilder(
          future: rootBundle.loadString("assets/manual/contents.md"),
          builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
            if (snapshot.hasData) {
              return Markdown(data: snapshot.data);
            }

            return Center(
              child: CircularProgressIndicator(),
          );
       }),
    );
  }

Is there a way to do it? Because Google hasn't helped at all and I am seriously doubting that it is possible.

like image 563
Carsten Brooks Avatar asked Aug 21 '20 17:08

Carsten Brooks


People also ask

What is markdown in flutter?

The flutter_markdown package renders Markdown, a lightweight markup language, into a Flutter widget containing a rich text representation. flutter_markdown is built on top of the Dart markdown package, which parses the Markdown into an abstract syntax tree (AST).


1 Answers

I had to create a variable outside of the class, and then make a getter and setter for it, then make the future builder a method and call setState(){} after setting the variable.

String file = "contents.md";
class _ManualState extends State<Manual> {

  @override
    Widget build(BuildContext context) {

        return Scaffold(
          appBar: AppBar(title: Text(getFile()),),
          body: displayMarkdown(getFile())
        );
      }
    FutureBuilder<String> displayMarkdown(String file){

        return FutureBuilder(
          future: DefaultAssetBundle.of(context).loadString
            ("assets/manual/" + file),
          builder: (BuildContext context, AsyncSnapshot<String> snapshot){
            if (snapshot.hasData) {
              return Markdown(data: snapshot.data, onTapLink: (link){
                setFile(link);
                setState((){});
              },
              );
            }
            return Center(
              child: CircularProgressIndicator(),
            );
          },
        );
      }
}
String getFile() {
  return file;
}

String setFile(String name) {
  file = name;
  return file;
}
like image 53
Carsten Brooks Avatar answered Oct 29 '22 15:10

Carsten Brooks