60 lines
1.4 KiB
Dart
60 lines
1.4 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:html/dom.dart' as dom;
|
|
import 'package:html/parser.dart' as parser;
|
|
|
|
class PostTextRenderer extends StatelessWidget {
|
|
const PostTextRenderer({
|
|
required this.htmlInput,
|
|
Key? key,
|
|
}) : super(key: key);
|
|
final String htmlInput;
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
dom.Document document = parser.parse(htmlInput);
|
|
final List<InlineSpan> children =
|
|
createSpansFromDoc(document.body!.children);
|
|
return SelectableText.rich(
|
|
TextSpan(
|
|
style: Theme.of(context).textTheme.bodyMedium,
|
|
text: "",
|
|
children: children,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
List<InlineSpan> createSpansFromDoc(List<dom.Element> elements) {
|
|
List<InlineSpan> result = [];
|
|
for (int i = 0; i < elements.length; i += 1) {
|
|
final e = elements[i];
|
|
result.add(
|
|
getSpanForElement(
|
|
e,
|
|
elements.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,
|
|
),
|
|
),
|
|
);
|
|
}
|