Dart network programming

Dart network programming

  • TCP server
  • TCP client
  • UDP server
  • UDP client
  • HTTP server and request
  • WebSocket
  • Server
  • Client

Dart network programming
The following provides various code examples of Dart's network programming. For specific protocol knowledge, please learn by yourself.


TCP server

import 'dart:convert';
import 'dart:io';

void main() {
  ServerSocket.bind(InternetAddress.loopbackIPv4, 8081)
  .then((serverSocket) {
    serverSocket.listen((socket) {


The above is a concise example, not very clear, equivalent to the following code

import 'dart:io';
import 'dart:convert';

void main() {



void startTCPServer() async{
  ServerSocket serverSocket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 8081);

  await for(Socket socket in serverSocket) {
    socket.cast<List<int>>().transform(utf8.decoder).listen((data) {
      print("from ${socket.remoteAddress.address} data:" + data);
      socket.add(utf8.encode('hello client!'));

TCP client
The corresponding concise expression is as follows

import 'dart:convert';
import 'dart:io';

void main() {
  Socket.connect('', 8081).then((socket) {
    socket.write('Hello, Server!');

import 'dart:convert';
import 'dart:io';

void main() {

void startTCPClient() async {
  Socket socket = await Socket.connect('', 8081);
  socket.write('Hello, Server!');


UDP server

import 'dart:io';
import 'dart:convert';

void main() {

// UDP 
void startUDPServer() async {
  RawDatagramSocket rawDgramSocket = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 8081);

  await for (RawSocketEvent event in rawDgramSocket) {
    if(event == RawSocketEvent.read) {
        rawDgramSocket.send(utf8.encode("UDP Server:already received!"), InternetAddress.loopbackIPv4, 8082);


UDP client

import 'dart:convert';
import 'dart:io';

void main() {

// UDP
void startUDPClent() async {
   RawDatagramSocket rawDgramSocket = await RawDatagramSocket.bind('', 8082);

   rawDgramSocket.send(utf8.encode("hello,world!"), InternetAddress(''), 8081);

  await for (RawSocketEvent event in rawDgramSocket) {
    if(event == RawSocketEvent.read) {


 HTTP server and request

import 'dart:io';

void main() {
      .bind(InternetAddress.loopbackIPv4, 8080)
      .then((server) {
        server.listen((HttpRequest request) {
            var subPathList = request.uri.path.split("/");

            if(subPathList.length >=3){
              request.response.write('Hello, ${subPathList[2]}');
             request.response.write('Hello, ');
            request.response.write('Welcome to test server!');


Browser input https://localhost:8080/greet/myaccess

The above is to use the browser to send a request to the server, then we use the code to simulate the browser to send the request

import 'dart:convert';
import 'dart:io';

void main() {
  HttpClient client = HttpClient();

    .then((HttpClientRequest request) {
      "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36");
      return request.close();
    .then((HttpClientResponse response) {

      response.transform(utf8.decoder).listen((contents) {


Usually, we will not directly use the httpnetwork request API provided by the Dart standard library , because the standard library library is still too cumbersome to use, and the third-party library is more concise and powerful. On Flutter, the main use of the diolibrary, the function is very powerful, in addition can also use the official httplibrary, more concise and refined, the link is as follows

  • http
  • dio


WebSocket is a protocol for full-duplex communication on a single TCP connection . Its appearance allows both the client and the server to actively push messages, which can be text or binary data. And there is no limitation of the same-origin policy, and there is no cross-domain problem. The identifier of the agreement is . Like https if encrypted .wswxs

WebSocket is an independent protocol created on TCP.

Websocket handshake through the 101 status code of HTTP / 1.1 protocol.

In order to create a Websocket connection, a request needs to be sent through the browser, and then the server responds. This process is usually called "handshaking"

The Web socket server uses a normal HTTP server to accept Web socket connections. The initial handshake is an HTTP request, which is then upgraded to a Web socket connection. The server uses the WebSocketTransformer upgrade request and listens to the data on the returned Web socket


import 'dart:io';

void main() async {
  HttpServer server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8083);
  await for (HttpRequest req in server) {
    if (req.uri.path == '/ws') {
      WebSocket socket = await WebSocketTransformer.upgrade(req);
      socket.listen((data) {
        print("from IP ${req.connectionInfo.remoteAddress.address}:${data}");
        socket.add("WebSocket Server:already received!");



import 'dart:io';

void main() async {
  WebSocket socket = await WebSocket.connect('ws://');
  socket.add('Hello, World!');

  await for (var data in socket) {
    print("from Server: $data");



Flutter Examples

  • Flutter Screenshot Widget - Take sceenshot as capture Image
  • Flutter Migrate App to Null Safety | Flutter 2.0
  • Flutter 2.0 Autocomplete TextField | RawAutocomplete Example
  • How to check installed Flutter Version
  • Info Popup Window | Create Popup window in Flutter Listview
  • Flutter Flow widget Example
  • Flutter GetX Storage | SharedPreferences
  • Send Email From Flutter Application | Attach html documents to email
  • Auto SMS OTP Read in Flutter Android
  • Download Files inside Listview | View Downloaded Files Flutter
  • Travel App Profile Page | Flutter Profile Page Example 2
  • Flutter Photo View | Image Zoom like Gallery App
  • Generate Signed APK for Flutter Application with Andorid Studio
  • Flutter Stacked Item ListView | Scroll Animation
  • Flutter Horizontal Listview with a Snap Effect
  • Infinite scrolling list with Flutter - Flutter Pagination Example
  • Flutter Audio Recording Example
  • Show BottomSheet Dialog On Screen Load - Flutter
  • Flutter Device Info | Read Device Info on Android and iOS devices with device_info plugin
  • Play YouTube video | YouTube API integration in Flutter
  • Dynamic ExpansionTile | Create Expansion List with Dynamic Data
  • Keyboard Request Focus Flutter Example | Handle Keyboard Next Button Events
  • Alert Dialog with Close Button Button
  • Share Location | How do i share current location in flutter
  • Copy flutter assets database inside application
  • End to End Encryption Decryption in Flutter
  • 3D Model Viewer in Flutter
  • File Read and Write Operations in Flutter Application - File I/O Operation
  • How to show Listview inside Dialog in Flutter
  • Store Image as String in SQLite Database in Flutter
  • Flutter interview questions with answers
  • A complete list of Flutter Libraries & Packages used for Flutter App development
  • Flutter bottom navigation - Simple BottomNavigationBar Example
  • How to Implement Pull To Refresh in Flutter?
  • User Registration and Login with Flutter and PHP Rest API
  • Design Complex UI in Flutter - Animated Drawer Widget
  • Building a Flutter app with DateTime Picker - Get DateTime From DateTime String
  • Dart Convert Map to List & List to Map
  • Create Circle Image in Flutter
  • Display multiple images inside grid like facebook in Flutter
  • Flutter consume data with Http Get and Http Post
  • Beehive Layout Widget in Flutter
  • Nested Listview (Listview inside Listview) in Flutter
  • How to Access Contacts in Flutter Application (Read and Make Phone calls)
  • MultiSelection Listview in Flutter with CheckboxListTile
  • Snackbar on Flutter (without Scaffold) using Flushbar
  • Flutter Transparent Background Page
  • Create Custom Widget in Flutter - Download Indicator
  • How To Open A Word or PDF Document On Android
  • Android TV Support with Flutter Framework
  • Check Network Connectivity Status in Flutter - Online & Offline Connectivity
  • Horizontal Scrollable Table in Flutter
  • REST API integration in Flutter with Retrofit
  • Expandable Card - BottomSheet Widget Flutter
  • Upload Image to Firebase Storage - Flutter (Android & Ios)
  • ListWheelScrollView Flutter Example
  • ChangeNotifierProvider - Flutter
  • Image Picker Flutter - Take Image From Camera or Gallery
  • How to show or hide widget in Flutter
  • Flutter - How to Run Background Task? Service
  • Text widget with read more or expand feature - Flutter
  • Create Profile Page in Flutter - UI
  • How to convert BASE64 string into Image with Flutter?
  • How to Show Back Button in Flutter
  • 10 Innovative apps that are built using Flutter
  • Flutter Push Notifications using flutter firebase messaging with example
  • How to create rating bar dialog in Flutter App
  • Flutter - Using DraggableScrollableSheet Widget Examples
  • How to parse RSS Feed in Flutter?
  • Flutter: Page View
  • Create native settings Page UI in Flutter
  • Delete data from Firestore - Delete Collection and subcollections
  • FloatingActionButton - Animated FloatingActionButton in Flutter
  • FireStore CRUD in Flutter - Social Application
  • Flutter Chat UI Tutorial
  • Flutter Food Ordering App Theme Template
  • Flutter Social Forum Application
  • Flutter State Management - ScopedModel
  • Flutter Todo Application Themes
  • Profile Themes
  • Login Themes
  • Localization Flutter - ChangeNotifier
  • How to show Checkbox at Right side of Text - Flutter
  • How to get Device Id in Flutter
  • Google Translator - Flutter
  • Building chat app with Flutter and Firebase
  • Shared Preferences - Data Persistence Flutter
  • Login Page - FrostedGlass Background Flutter
  • Simple Animation in Flutter
  • Settings Button - Flutter Popup Menu Button
  • Color Picker - Flutter Material Color Picker
  • Read Inbox Messages - Flutter SMS Retriever
  • Social Auth Buttons - Flutter (Google,Facebook,Twitter,Microsoft,Linked)
  • Credit Card Validator - Flutter
  • StreamBuilder - Flutter
  • Switch Button-Custom Switch-Flutter
  • Custom Toast - Flutter
  • Text Shadows in Flutter
  • How to load Html Content in Flutter
  • Firebase authentication & Google sign in using Flutter
  • How to add Firebase setup in Flutter
  • Flutter Fingerprint Authentication
  • Download Files in Flutter (Pdf, Json, Image etc) With Progress : Flutter Advance
  • Flutter Custom Buttons - How to Create Custom Buttons in Flutter?
  • Flutter Responsive Admin Template -2
  • Flutter Responsive Admin Template
  • Flutter Facebook Login - A Complete Guide to Facebook login with Flutter
  • Flutter - How to create Digital Signature pad (ESignature iOS and Android)
  • Flutter Future Builder
  • Flutter Radio Groups - How to make a list of grouped radio buttons in flutter
  • Form Builder in Flutter - Form Validation | RRTutors
  • Make Shimmer Effect in Flutter
  • Flutter Voice Recognition- Speech To Text - Voice Based Search
  • Text-to-Speech Flutter Plugin (Android & iOS)
  • Flutter - Page Navigation, Navigator and Routes - How to get Result from Screen
  • Flutter Form & Form-Fields widgets With Login Screen
  • Appbar Search | Implementing Search action with AppBar in flutter
  • Flutter Screen Navigation with Animation
  • Flutter - Bottomnavigationbar - PageView - Reload Page - KeepLive Pages
  • Flutter Stateful widget - Part3 - InheritedWidget Example - Sample Post List
  • Flutter Stateful widget - Part2 - How to Access State of Widget
  • Flutter Stateful widget - Part1 - Introduction - Lifecycle Methods
  • Push Notification in Flutter - Local Notification Part -2
  • Push Notification in Flutter - Local Notification
  • PIN Input Field in Flutter
  • Building Beautiful UI Interfaces with Flutter-Basic Components
  • Flutter - How to use Lottie Animations in Flutter
  • How to display Text Vertically
  • Flutter SafeArea - Handle start position of Widgets in the screen
  • Flutter Carousel - Swiper Banners
  • SelectableText widget vs Text widget Flutter - Text copy to Clipboard
  • Flutter Sensors - Accelerator Mobile Shake Events
  • How To Use Custom Icons in Flutter
  • Flutter - Custom Sticky Headers
  • Webview in flutter - Open Local HTML file in to webview - Open URL in Webview- handle Javascript function in webview
  • Flutter - How can draw route on google map between two locations?
  • Current Location On Maps - Flutter, Fetch Current Location Address.
  • How to dynamically change the theme in Flutter - ThemeProvider
  • Show Multiple Markers on Google Maps - Flutter infowindow example
  • Google Maps in Flutter, How to Load Google Maps
  • Flutter - ListView - Search Filter - NewsApplication
  • TabBar in Flutter, Custom TabBar, BottomNavigationbar, Different Styles of TabBar
  • Flutter GridView with Builder Constructor
  • Flutter GridView and Different ways of Constructors
  • ToogleBar - Flutter
  • Read Json file from assets folder - Flutter
  • Expandable Listview | Expansion/Collapse view | ExpansionTile
  • Flutter - Drag & Drop Listview - Reorderable Listview
  • Bottom Navigation Bar - TabBarView
  • Firebase Integration, Firebase Authentication, Firestore | RRTutors
  • Flutter - Dashboard App | RRTutors
  • Flutter SQFLite Tutorial: Implement SQFLite database in Flutter | RRTutors
  • Flutter Button Widgets | RRTutors
  • Flutter Widgets | RRTutors
  • Flutter First Application | RRTutors
  • Flutter Introduction | RRTutors
  • Android Examples

  • Android Onboarding Screen UI with ViewPager
  • What is View Binding | Android View Binding Example
  • How do i use Navigationview in android with Kotlin
  • Start activity From Fragment Android Example
  • Android ViewModel Interview Questions and Answers
  • GooglePlay Inapp Review API Integration in Android Application
  • Easy way To Convert Website Into Mobile Application Android
  • Order and Un Order List in Android Textview Kotlin
  • Dialog Fragment with Scroll view - doesn't scroll | Android studio Project
  • Color Picker | Android Color Picker view to set Color to Bulb View
  • Jetpack Compose Tutorial | Jetpack Compose Basics
  • Get List of devices connected to Same Network in Android Programmatically
  • How to display Listview inside Dialog in Android | Kotlin Example
  • How to add Image and text in Sqlite Database and Display it in recyclerView with kotlin
  • Getting Started with Facebook Analytics for Mobile Apps
  • Android Job Scheduler with Kotlin
  • Understanding The Lifecycle of Custom View In Android - Kotlin
  • How to create pagination text in Android using Kotlin?
  • Re-size and Compress Image in Android Studio
  • Dependency Injection - What is Dependency Injection?
  • One to One chat application using Kotlin - Android
  • Integrating UPI payments in an Android application
  • Android Jetpack Tutorials : LiveData
  • Android ViewModel Tutorial : Jetpack Tutorials : View Model Introduction
  • How To Use Jet Pack Components BottomNavigationView With Navigation Ui
  • In-App purchase Google Play Billing - Play Billing Library
  • Taking a screenshot of a particular view
  • Handler in Android
  • Add Google Analytics in Android Application
  • Adding Firebase to Android App
  • How to create Circular Seekbar in Android
  • Android Q - Settings Panel
  • Image Slider in Android
  • Create and Display Notification on Android
  • Foreground Service Android
  • How to change Orientation programmatically in Android
  • How to uninstall/delete APK Programmatically in Android
  • Android - Kotlin - ContextMenu - How to Create Contextmenu in Android?
  • Kotlin - How to handle swipe Gesture in Android Application?
  • Android Switch (ON / OFF) Button - Custom Style
  • Android - Softinput Keyboard open and close programmatically
  • Kotlin - Android Textwatcher Example
  • How to set the part of the Android TextView as clickable - ClickableSpan
  • Kotlin – Android Color Picker Example
  • Create Custom Snackbar - How to use snackbar in Android?
  • How to call an activity method from fragment | Start Activity from Fragment
  • How to Create Android Calculator Application
  • Android kotlin - SeekBar example
  • Android Animations - Rotate,Scale,Translate,Zoom animations in Android
  • Live WallPaper - How to Make Interactive Live Video Wallpapers Using Kotlin Android
  • Kotlin Create Slider With Page Indicator Using ViewPager Example
  • Android kotlin - AlertDialog example
  • Android - Kotlin Success and Error Dialogs with Lottie Animation
  • Android-Kotlin - Circular Imageview with Border
  • SwipeRefreshLayout - Android
  • Android Bottom Sheet with BottomSheetDialogFragment
  • Android Exoplayer - Play Audio/Video files in Android.
  • What is Retrofit and how to use Retrofit in Android?
  • Firebase Project - Android
  • Android Video Player Example
  • Test
  • Programming Vocabulary
  • Moving Map Under Marker Like UBER: Maps Android, Kotlin | RRTutors
  • Circular Progress bar with Thumb | RRTutors