Micro Serve
The micro_serve
package for Flutter is designed to initialize an HTTP server that efficiently manages requests and server-side operations within applications using raw Dart code.
Features
-
HTTP Handling: Manage incoming HTTP requests and send responses.
-
Routing: Define routes (GET, POST, PUT, DELETE, PATCH) and link them to request handlers.
-
Request Parsing: Read and parse query parameters, headers and body from requests.
-
Response Handling: Create and send responses with status codes and content.
-
Error Handling: Gracefully manage errors and send appropriate error responses.
Getting started
Add the package to your
pubspec.yaml
file:
dependencies:
micro_serve: <latest version>
Open (android/app/src/main/)
AndroidManifest.xml
and add this line:
<manifest xmlns:android="...">
<uses-permission android:name="android.permission.INTERNET"/> <!-- Add this -->
<application....>
</manifest>
macOS apps must allow network access in the relevant
*.entitlements
files:
<key>com.apple.security.network.client</key>
<true/>
Import the Package:
import 'package:micro_serve/micro_serve.dart';
Initialize the Server:
void main() {
final MicroServe server = MicroServe();
server.get("/test", (ServerContext serverContext) async {
final Response response = Response(
statusCode: 200,
data: "Welcome Micro-Serve",
);
serverContext.send(response);
});
server.listen(ipAddress: "127.0.0.1", port: 3000);
}
Usage
Create an Object of MicroServe:
final MicroServe _server = MicroServe();
Server On Function:
void _serverOn() async {
//Define Routes
_server.put("/update", _updateTask);
//Get WiFi IP Address
final String? lanWifiIp = await Network.getIp(NetworkType.wlan);
const int port = 3000;
// Server Start
_server.listen(
ipAddress: lanWifiIp,
port: port,
callBack: (_) {
print("Server initiated");
},
);
}
Server Off Function:
void _serverOff() async {
await _server.close();
}
Handler Function:
void _updateTask(ServerContext serverContext) async {
//Get Client Request From Request() Of ServerContext
final Request request = serverContext.request;
final int id = int.parse(request.queryParams["id"]!);
final String name = jsonDecode(request.body)["name"];
final bool isDone = jsonDecode(request.body)["isDone"];
final String? apiKey = request.headers["api-key"];
// print("Client IP: ${serverContext.connectionInfo.address}");
//Create an Object of Response() to Send Client
final Response response = Response();
if (apiKey != "abcd1234") {
//Edit Response Object as Preference 1
response.statusCode = HttpStatus.unauthorized_401.code;
response.data = {"message": "invalid api key"};
} else if (!_taskStore.containsKey(id)) {
//Edit Response Object as Preference 2
response.statusCode = HttpStatus.notFound_404.code;
response.data = {"message": "not found"};
} else {
_taskStore[id]!.name = name;
_taskStore[id]!.isDone = isDone;
//Edit Response Object as Preference 3
response.statusCode = HttpStatus.accepted_202.code;
response.data = {"message": "updated successfully"};
}
//Send Response to Client
serverContext.send(response);
}
API Reference
Method
PUT
:
http://ip:port/update?id=1
Headers:
key | value |
---|---|
api-key | abcd1234 |
Body:
{
"name" : "mh task",
"isDone" : true
}
Limitation
Android | iOS | MacOS | Web | Linux | Windows |
---|---|---|---|---|---|
✅ | ✅ | ✅ | ❌ | ✅ | ✅ |
The functionality is not supported on Web.
Additional information
Micro Serve
plugin is developed by Mahadi Hassan