flutter_html_class_to_css_converter_extension 0.1.0
flutter_html_class_to_css_converter_extension: ^0.1.0 copied to clipboard
A flutter_html extension that converts class attributes to inline CSS styles.
Example #
This package is the plumbing other flutter_html class-to-CSS extensions build
on. Using it means writing a resolver that maps class names to inline CSS, then
exposing it as an HtmlExtension.
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html_class_to_css_converter_extension/flutter_html_class_to_css_converter_extension.dart';
/// Maps a single `highlight` class onto inline CSS.
class HighlightResolver implements ClassListCssResolver {
/// Keep this cheap: it runs for every element.
@override
bool matches(List<String> orderedClasses) =>
orderedClasses.contains('highlight');
/// Return parseable declarations, without braces. `''` means "nothing to do".
@override
String resolve(List<String> orderedClasses) =>
'background-color: #ffff00; color: #000000';
}
/// Wires the resolver up as an extension `Html` can use.
class HighlightExtension extends ClassToInlineCssExtension {
const HighlightExtension();
@override
List<ClassListCssResolver> get resolvers => [HighlightResolver()];
}
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
home: Scaffold(
body: Html(
data: '''
<p>Plain text, untouched.</p>
<p class="highlight">This paragraph is highlighted.</p>
<p class="highlight" style="padding: 8px;">
Existing inline styles are preserved and merged.
</p>
''',
extensions: const [HighlightExtension()],
),
),
);
}
void main() => runApp(const ExampleApp());
How it behaves #
- The extension runs during
flutter_html'spreStylingstep, merging resolved CSS into each element'sstyle=""attribute, so the result flows through the normal styling pipeline. - Elements whose classes match no resolver are left completely alone.
- Pre-existing inline styles are kept; resolved declarations are appended, so
the element's own
style=""wins where the two overlap.
Multiple resolvers #
resolvers is a list, and order matters when two resolvers write the same
property. Later ones win:
class MyExtension extends ClassToInlineCssExtension {
const MyExtension();
@override
List<ClassListCssResolver> get resolvers => [
HighlightResolver(),
SomeOtherResolver(),
];
}
Restricting which tags are processed #
Pass supportedTags to limit the elements the extension applies to, and to
register non-standard tag names so flutter_html does not discard them:
class MyExtension extends ClassToInlineCssExtension {
const MyExtension() : super(supportedTags: const {'div', 'span', 'my-widget'});
@override
List<ClassListCssResolver> get resolvers => [HighlightResolver()];
}