HTTP Server running on a Mobile app with Flutter
This article helps you to understand Creating a server running on a mobile device with a flutter application.
So… Let’s dig in
Initially… Let’s understand how a basic server with dart works… We are going to use http plugin for sending request and response.
Importing I/O ( Input-Output ) & async package :
import 'dart:io';
import 'dart:async';
In order to perform actions such as run/request/response our main function or user defined function need to be asynchronous.
main() async {
}
Initializing server on your IP Address :
Creating a server and referencing to a variable.
var server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080);
We can also use try-cache block for verifying weather the server actually started or something went wrong…
try{
var server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080);print("Server running on IP : "+server.address.toString()+" On Port : "+server.port.toString());
}catch(e){ print("Something went wrong while creating a server...");
}
Listening for requests :
Listening for requests to send responses to clients
await for (var request in server) {
request.response
..headers.contentType = new ContentType("text", "plain", charset: "utf-8")
..write('Hello, world')
..close();
}
Complete code for Running a server with Flutter :
import 'package:flutter/material.dart';import 'dart:io';void main(){runApp(MaterialApp(home: Home(),));}class Home extends StatefulWidget {@override_HomeState createState() => _HomeState();}class _HomeState extends State<Home> {String statusText = "Start Server";startServer()async{setState(() {statusText = "Starting server on Port : 8080";});var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8080);print("Server running on IP : "+server.address.toString()+" On Port : "+server.port.toString());await for (var request in server) {request.response..headers.contentType = new ContentType("text", "plain", charset: "utf-8")..write('Hello, world')..close();}setState(() {statusText = "Server running on IP : "+server.address.toString()+" On Port : "+server.port.toString();});}@overrideWidget build(BuildContext context) {return Scaffold(body: Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: <Widget>[RaisedButton(onPressed: (){startServer();},child: Text(statusText),)],),));}}
Try running the following code on a mobile app…
After running the mobile app start the server.
After, Starting the server keep it in background and open a favorite web browser on your mobile device and type your device IP address followed with a port value. Ex: http://192.168.43.63:8080/
Once you sent the request you can see “Hello World” on the web browser.