Home > Enterprise >  How to display HTML text in Flutter in desktop
How to display HTML text in Flutter in desktop

Time:08-25

I want to display a paragraph in HTML that has various bold text and links within the tag using flutter on a desktop platform. I've come across "flutter_html", but the only supported platforms are for iOS and Android. Is there any other library that could display HTML text in a desktop environment? If there are none, are there any other ways to make this possible?

CodePudding user response:

You can use flutter_html in desktop app.

Try my code below:

import 'package:html/dom.dart' as dom;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:html/parser.dart' show parse;
import 'package:flutter_html/flutter_html.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.yellow,
      ),
      home: const HomePage(title: 'This Is Desktop'),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  HomePageState createState() => HomePageState();
}

class HomePageState extends State<HomePage> {
  @override
  void initState() {
    parseHtml();
    super.initState();
  }

  Future<dom.Document> parseHtml() async {
    return parse(await rootBundle.loadString('static/index.html'));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: FutureBuilder<dom.Document>(
          future: parseHtml(),
          builder:
              (BuildContext context, AsyncSnapshot<dom.Document> snapshot) {
            if (snapshot.hasData) {
              return Html(data: snapshot.data?.outerHtml);
            } else {
              return const Center(
                child: Text("Loading"),
              );
            }
          }),
    );
  }
}

However, some tag has no effect. For example img tag not showing image, a tag only have link style but won't open a browser to a link when you click on it.

And some of css styles are not support, like flex.

  • Related