start method Null safety

Future<void> start()

Starts the server on http://localhost:[port]/.

NOTE for iOS: For the iOS Platform, you need to add the NSAllowsLocalNetworking key with true in the Info.plist file (See ATS Configuration Basics):

<key>NSAppTransportSecurity</key>
<dict>
   <key>NSAllowsLocalNetworking</key>
   <true/>
</dict>

The NSAllowsLocalNetworking key is available since iOS 10.

Implementation

Future<void> start() async {
  if (this._started) {
    throw Exception('Server already started on http://localhost:$_port');
  }
  this._started = true;

  var completer = Completer();

  runZonedGuarded(() {
    HttpServer.bind('127.0.0.1', _port).then((server) {
      print('Server running on http://localhost:' + _port.toString());

      this._server = server;

      server.listen((HttpRequest request) async {
        Uint8List body = Uint8List(0);

        var path = request.requestedUri.path;
        path = (path.startsWith('/')) ? path.substring(1) : path;
        path += (path.endsWith('/')) ? 'index.html' : '';

        try {
          body = (await rootBundle.load(path)).buffer.asUint8List();
        } catch (e) {
          print(e.toString());
          request.response.close();
          return;
        }

        var contentType = ['text', 'html'];
        if (!request.requestedUri.path.endsWith('/') &&
            request.requestedUri.pathSegments.isNotEmpty) {
          var mimeType = MimeTypeResolver.lookup(request.requestedUri.path);
          if (mimeType != null) {
            contentType = mimeType.split('/');
          }
        }

        request.response.headers.contentType =
            ContentType(contentType[0], contentType[1], charset: 'utf-8');
        request.response.add(body);
        request.response.close();
      });

      completer.complete();
    });
  }, (e, stackTrace) => print('Error: $e $stackTrace'));

  return completer.future;
}