Try it yourself with our free Html Beautifier tool — runs entirely in your browser, no signup needed.

How to Format HTML in Dart

How to format HTML in Dart

Introduction

Formatting HTML in Dart is a crucial task for web developers who want to ensure their web pages are structured and presented correctly. Properly formatted HTML enhances readability, maintainability, and search engine optimization (SEO). Dart provides several libraries and tools to parse and format HTML, but in this guide, we will focus on using the html package to format HTML in Dart.

Quick Example

Here's a minimal example of how to format HTML using the html package:

import 'package:html/parser.dart';
import 'package:html/dom.dart';

void main() {
  String htmlString = '<html><body>Hello, <span>World!</span></body></html>';
  Document document = parse(htmlString);
  String formattedHtml = document.outerHtml;
  print(formattedHtml);
}

This code will output the formatted HTML string.

Step-by-Step Breakdown

Let's break down the code example:

  1. import 'package:html/parser.dart';: We import the html/parser library, which provides the parse function to parse HTML strings.
  2. import 'package:html/dom.dart';: We import the html/dom library, which provides the Document class to represent the parsed HTML document.
  3. String htmlString = '<html><body>Hello, <span>World!</span></body></html>';: We define a sample HTML string.
  4. Document document = parse(htmlString);: We parse the HTML string using the parse function, which returns a Document object.
  5. String formattedHtml = document.outerHtml;: We access the formatted HTML string using the outerHtml property of the Document object.
  6. print(formattedHtml);: We print the formatted HTML string to the console.

Handling Edge Cases

Empty/null input

When handling empty or null input, we should check for these cases before attempting to parse the HTML string:

String htmlString = '';
if (htmlString != null && htmlString.isNotEmpty) {
  Document document = parse(htmlString);
  // ...
} else {
  print('Input is empty or null');
}

Invalid input

When handling invalid input, we should catch any exceptions thrown by the parse function:

try {
  Document document = parse(htmlString);
  // ...
} catch (e) {
  print('Invalid input: $e');
}

Large input

When handling large input, we should consider using a streaming parser or splitting the input into smaller chunks:

String largeHtmlString = '...'; // large HTML string
List<String> chunks = largeHtmlString.split('<!-- chunk -->');
chunks.forEach((chunk) {
  Document document = parse(chunk);
  // ...
});

Unicode/special characters

When handling Unicode or special characters, we should ensure that the input string is encoded correctly:

String htmlString = '<html><body>Hello, &#x1F600;</body></html>'; // Unicode character
Document document = parse(htmlString);
// ...

Common Mistakes

Mistake 1: Not checking for null input

Wrong code:

String htmlString = null;
Document document = parse(htmlString);

Corrected code:

String htmlString = null;
if (htmlString != null) {
  Document document = parse(htmlString);
  // ...
}

Mistake 2: Not handling exceptions

Wrong code:

Document document = parse(htmlString);

Corrected code:

try {
  Document document = parse(htmlString);
  // ...
} catch (e) {
  print('Invalid input: $e');
}

Mistake 3: Not encoding special characters

Wrong code:

String htmlString = '<html><body>Hello, !</body></html>'; // Unicode character
Document document = parse(htmlString);

Corrected code:

String htmlString = '<html><body>Hello, &#x1F600;</body></html>'; // Unicode character
Document document = parse(htmlString);

Performance Tips

  1. Use caching: Cache the parsed HTML documents to avoid re-parsing the same input multiple times.
  2. Use streaming parsing: Use a streaming parser to parse large HTML inputs in chunks, reducing memory usage.
  3. Avoid unnecessary parsing: Only parse the HTML input when necessary, and avoid parsing the same input multiple times.

FAQ

Q: How do I install the html package?

Answer: Add the html package to your pubspec.yaml file and run pub get.

Q: How do I parse HTML fragments?

Answer: Use the parseFragment function instead of parse to parse HTML fragments.

Q: How do I handle HTML entities?

Answer: Use the htmlEscape function to escape HTML entities, and htmlUnescape to unescape them.

Q: Can I use the html package with Dart 2?

Answer: Yes, the html package is compatible with Dart 2.

Q: How do I report issues or request features?

Answer: Open an issue on the html package's GitHub repository.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp