Dart Core Libraries 'dart:html'

Dart Core Libraries 'dart:html'

The dart:html library in Dart is specifically designed for web applications and provides APIs for interacting with the Document Object Model (DOM) and handling events in the context of a web browser.

It enables Dart developers to create dynamic and interactive web user interfaces using familiar HTML elements and JavaScript-like event handling.

Key Features of dart:html

1. Manipulating the DOM

The dart:html library allows you to manipulate the DOM (Document Object Model) of a web page using Dart code. You can create, modify, and query HTML elements, update their attributes and styles, and append them to the document.

Example - Creating and Appending Elements:

import 'dart:html';

void main() {
  // Create a new paragraph element
  ParagraphElement paragraph = ParagraphElement();
  paragraph.text = 'Hello, Dart!';

  // Append the paragraph element to the document body

2. Handling Events

You can use dart:html to handle user interactions and browser events, such as clicks, keyboard input, form submissions, and more.

Example - Handling Click Events:

import 'dart:html';

void main() {
  ButtonElement button = ButtonElement();
  button.text = 'Click me';

  // Add a click event listener to the button
  button.onClick.listen((MouseEvent event) {
    print('Button clicked!');

  // Append the button to the document body

3. Making HTTP Requests

The dart:html library provides utilities for making HTTP requests from a web browser using XMLHttpRequest or Fetch API.

Example - Making an HTTP GET Request:

import 'dart:html';

void main() async {
  var response = await HttpRequest.getString('https://api.example.com/data');
  print('Response: $response');

4. Working with Forms

You can easily interact with HTML forms using dart:html, accessing form elements, handling form submissions, and validating user input.

Example - Accessing Form Data:

import 'dart:html';

void main() {
  FormElement form = document.querySelector('#myForm') as FormElement;
  form.onSubmit.listen((Event event) {
    event.preventDefault(); // Prevent the default form submission
    print('Form submitted!');
    print('Input value: ${form['inputField'].value}');