2022-08-06 16:46:31 +00:00
|
|
|
import 'package:flutter/material.dart';
|
2022-08-06 20:13:12 +00:00
|
|
|
import 'package:html/dom.dart' as dom;
|
|
|
|
import 'package:html/parser.dart' as parser;
|
2022-08-06 16:46:31 +00:00
|
|
|
|
|
|
|
class PostTextRenderer extends StatelessWidget {
|
|
|
|
const PostTextRenderer({
|
2022-08-06 16:56:33 +00:00
|
|
|
required this.htmlInput,
|
2022-08-06 16:46:31 +00:00
|
|
|
Key? key,
|
|
|
|
}) : super(key: key);
|
2022-08-06 16:56:33 +00:00
|
|
|
final String htmlInput;
|
2022-08-06 16:46:31 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
Widget build(BuildContext context) {
|
2022-08-06 20:13:12 +00:00
|
|
|
dom.Document document = parser.parse(htmlInput);
|
|
|
|
final List<InlineSpan> children = createSpansFromDoc(document);
|
|
|
|
return SelectableText.rich(TextSpan(
|
|
|
|
text: "",
|
|
|
|
children: children,
|
|
|
|
));
|
2022-08-06 16:46:31 +00:00
|
|
|
}
|
|
|
|
}
|
2022-08-06 20:13:12 +00:00
|
|
|
|
|
|
|
List<InlineSpan> createSpansFromDoc(dom.Document document) {
|
|
|
|
List<InlineSpan> result = [];
|
|
|
|
for (int i = 0; i < document.body!.children.length; i += 1) {
|
|
|
|
final e = document.body!.children[i];
|
|
|
|
result.add(
|
|
|
|
getSpanForElement(
|
|
|
|
e,
|
|
|
|
document.body!.children.length,
|
|
|
|
i,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
InlineSpan getSpanForElement(dom.Element e, int bodyLength, int pos) {
|
|
|
|
if (e.toString() == "<html p>") {
|
|
|
|
return handleParagraph(e, bodyLength, pos);
|
|
|
|
}
|
|
|
|
return TextSpan(text: e.text);
|
|
|
|
}
|
|
|
|
|
|
|
|
InlineSpan handleParagraph(dom.Element e, int bodyLength, int pos) {
|
|
|
|
String text = e.text;
|
|
|
|
return WidgetSpan(
|
|
|
|
child: Padding(
|
|
|
|
padding: const EdgeInsets.fromLTRB(0, 4, 0, 4),
|
|
|
|
child: SelectableText(text),
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|