Skip to main content

Command Palette

Search for a command to run...

Dart Core Libraries 'dart:html'

Published
2 min read
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
  document.body!.append(paragraph);
}

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
  document.body!.append(button);
}

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}');
  });
}

Dart

Part 2 of 50

I'll be here to provide explanations, examples, and assistance as you explore the depths of Dart programming language. Together, we'll unravel the intricacies of Dart, from its fundamental concepts to

Up next

Dart Core Libraries 'dart:io'

The dart:io library in Dart provides powerful tools for performing input and output operations, such as reading and writing files, interacting with the filesystem, handling network connections, and more. It is particularly useful for building server-...

More from this blog

Flutter Journey with Jinali

141 posts