Tuesday, August 22, 2023

Set Up Dart Server: Beginner's Easy Guide

1. Introduction to Dart Server

Dart server refers to building a server using the Dart programming language developed by Google. The Dart language features efficient code writing and high performance, making it easy to set up a server. You can explore the basic concepts and environment settings required to build a server and create a Dart server on your own.

When working with web servers, Dart can be a powerful tool as a backend language for the following reasons:

  • Efficient code writing with concise syntax
  • Easy-to-use language tools and libraries
  • Fast code execution and high performance
  • High portability and compatibility as a language feature

In the next chapter, we will explore the specific environment settings and basic concepts. You will be able to understand the initial setup process and build Dart servers using various features.

2. Environment Settings and Basic Concepts

In this section, we will explore the environment settings and basic concepts required to build a Dart server. You will set up the necessary tools and environments, understand the process of writing and executing the server.

2.1. Dart Installation and Environment Settings

First, you need to install the Dart SDK. You can install it by following these steps:

  1. Visit the official Dart website (https://dart.dev/).
  2. Go to the Get Started page and download the Dart SDK for your supported operating system.
  3. Extract the downloaded files and add the Dart SDK installation path to the environment variable 'PATH'.
  4. Run 'dart --version' in the terminal to verify the installation status.

You have now prepared the necessary development tools and environment. The next step is to set up the development environment and editor.

2.2. Development Environment and Editor Settings

Choose a code editor of your liking and install the relevant Dart plugins and packages. The recommended code editors and corresponding settings are as follows:

  • Visual Studio Code: Install the Dart plugin and specify the Dart SDK path in the settings.
  • IntelliJ IDEA: Install the Dart plugin and specify the Dart SDK path in the settings.
  • Other editors: Install the appropriate Dart plugins for most editors and follow the same settings.

You have now set up all development tools and environments for developing Dart servers. In the next chapter, we will explore how to build a Dart server.

3. Dart Server Configuration

In this chapter, we will introduce how to configure a Dart server. By creating a simple web server, we will learn how to handle HTTP requests.

3.1. Installing Required Packages

First, you need to install packages required for server configuration. Here, we will use a Dart package called 'shelf'. Create a 'pubspec.yaml' file and add the following content:

name: my_server
dependencies:
  shelf: ^1.0.0

Run the 'pub get' command in the terminal to install the 'shelf' package.

3.2. Writing a Basic Web Server

Now, let's write a basic web server. You need to create a 'main' function to start the server and a 'handleRequest' function to handle requests. Create a 'server.dart' file and write the following code:

import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';

void main() async {
  // Create request handler
  var handler = Pipeline().addMiddleware(logRequests()).addHandler(handleRequest);

  // Start server
  var server = await serve(handler, 'localhost', 8080);
  print('Serving at http://${server.address.host}:${server.port}');
}

// Request handling function
Response handleRequest(Request request) {
  return Response.ok('Hello from Dart server!');
}

To run the server, execute the 'dart run server.dart' command in the terminal. Visit 'http://localhost:8080' in your web browser to see the message returned by the created web server.

3.3. Handling Paths and HTTP Methods

Expand the web server code to handle multiple paths and HTTP methods. Use the 'shelf_router' package for simplified handling. Add the following content to 'pubspec.yaml':

dependencies:
  shelf_router: ^1.0.0

And modify the server code as follows:

import 'package:shelf_router/shelf_router.dart';

void main() async {
  // Create router
  final router = Router();

  // Handle paths and methods
  router.get('/', (Request request) {
    return Response.ok('Welcome to Dart server!');
  });

  router.get('/hello', (Request request) {
    return Response.ok('Hello from Dart server!');
  });

  // Add middleware and router
  var handler = Pipeline().addMiddleware(logRequests()).addHandler(router);

  // Start server
  var server = await serve(handler, 'localhost', 8080);
  print('Serving at http://${server.address.host}:${server.port}');
}

The web server now provides different responses for each path. You can visit 'http://localhost:8080' and 'http://localhost:8080/hello' in your web browser to verify this.

4. Examples and Practical Applications

In this chapter, we will examine how to utilize Dart servers using a simple "To-Do List" API example. In this example, we will use a simple in-memory database to store information and communicate with the client using JSON format.

4.1. Installing and Setting up Required Packages

First, you need to install the 'shelf' package along with 'json_annotation', 'json_serializable', and 'build_runner' packages to handle JSON data. Add the following content to the 'pubspec.yaml' file:

dependencies:
  json_annotation: ^4.0.0

dev_dependencies:
  json_serializable: ^4.0.0
  build_runner: ^2.0.0

Run the 'pub get' command in the terminal to install the packages.

4.2. Creating the Model

Create a 'Todo' model to be stored in the in-memory database. Create a 'lib/models/todo.dart' file and write the following code:

import 'package:json_annotation/json_annotation.dart';

part 'todo.g.dart';

@JsonSerializable()
class Todo {
  final int id;
  final String title;
  final bool completed;

  Todo({required this.id, required this.title, required this.completed});

  factory Todo.fromJson(Map<String, dynamic> json) => _$TodoFromJson(json);
  Map<String, dynamic> toJson() => _$TodoToJson(this);
}

Execute the 'dart run build_runner build' command in the terminal to generate the required files for the model class.

4.3. Writing the API Server

Write the To-Do List API server using the 'shelf' library and 'shelf_router' package. Write the following code in the 'server.dart' file:

import 'dart:convert';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf/shelf_io.dart';
import 'lib/models/todo.dart';

int _todoCounter = 1;
final _todos = <Todo>[];

void main() async {
  var app = Router();

  app.get('/todos', (Request request) {
    final todosJson = _todos.map((t) => t.toJson()).toList();
    return Response.ok(json.encode(todosJson), headers: _jsonHeader);
  });

  app.post('/todos', (Request request) async {
    final jsonString = await request.readAsString();
    final newTodo = Todo.fromJson(json.decode(jsonString)..['id'] = _todoCounter++);
    _todos.add(newTodo);
    return Response.ok(json.encode(newTodo.toJson()), headers: _jsonHeader);
  });

  var handler = Pipeline()
      .addMiddleware(logRequests())
      .addMiddleware(addHeader('Content-Type', 'application/json'))
      .addHandler(app);

  var server = await serve(handler, 'localhost', 8080);
  print('Todo API server listening at http://${server.address.host}:${server.port}');
}

const _jsonHeader = {'Content-Type': 'application/json'};

This written code serves GET (querying) and POST (adding new) To-Do lists features at the '/todos' path. In this code, you can see how to communicate with clients using a simple in-memory database and JSON format.

4.4. API Testing

To test the API server, run the 'dart run server.dart' command in the terminal to start the server. Then, you can test the written API using a CLI tool like curl or a GUI tool like Postman.

Through this example, we have examined how to implement actual features using Dart servers. In the last chapter, let's summarize the article and review the conclusions we have taken away about Dart servers.

5. Conclusion and Outlook of Dart Server

In this article, we have examined how to build and utilize Dart servers. We started with setting up the environment and then proceeded to create a basic web server. Later, we looked into how Dart servers actually work by implementing a "To-Do List" API example.

5.1. Advantages of Dart Server

Here are some advantages of Dart server:

  • Fast execution speed and high performance
  • Increased development productivity due to language simplicity and ease of structure
  • Consistent code reuse and provision of clients and server-side development using a single language
  • Easy-to-use package and library collection

5.2. Disadvantages of Dart Server

There are also some disadvantages to Dart server:

  • Relatively few companies/projects adopting it so far
  • Compared to other popular languages, the community and ecosystem are relatively small

5.3. Outlook of Dart Server

Dart server holds great potential for developing both client and server sides with the same language. Moreover, Dart supports various frameworks such as Flutter and AngularDart for web, mobile, and server development, enabling consistent development across platforms.

Of course, Dart is still not as widely used and supported as other languages like C#, Java, or JavaScript in terms of community size and ecosystem. However, one could expect that as these drawbacks improve over time, Dart server could be used in more places.

Finally, consider the pros and cons of Dart server in order to make the appropriate choice based on your project requirements, consistent technology stack, and future support and updates.

Hopefully, this article has provided valuable insights into building and utilizing Dart servers. We wish you success in applying Dart servers to future projects.


0 개의 댓글:

Post a Comment