jaguar_flutter_asset.dart 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import 'package:flutter/services.dart';
  2. import 'package:jaguar/jaguar.dart';
  3. /// Serves static files from Flutter assets.
  4. ///
  5. /// Example:
  6. ///
  7. /// final server = Jaguar();
  8. /// server.addRoute(serveFlutterAssets());
  9. /// await server.serve();
  10. Route serveFlutterAssets(
  11. {String path: '*',
  12. bool stripPrefix: true,
  13. String prefix: '',
  14. Map<String, String>? pathRegEx,
  15. ResponseProcessor? responseProcessor}) {
  16. Route route;
  17. int skipCount = -1;
  18. route = Route.get(path, (ctx) async {
  19. Iterable<String> segs = ctx.pathSegments;
  20. if (skipCount > 0) segs = segs.skip(skipCount);
  21. String lookupPath =
  22. segs.join('/') + (ctx.path.endsWith('/') ? 'index.html' : '');
  23. final body = (await rootBundle
  24. .load('packages/polkawallet_sdk/assets/$prefix$lookupPath'))
  25. .buffer
  26. .asUint8List();
  27. String? mimeType;
  28. if (!ctx.path.endsWith('/')) {
  29. if (ctx.pathSegments.isNotEmpty) {
  30. final String last = ctx.pathSegments.last;
  31. if (last.contains('.')) {
  32. mimeType = MimeTypes.fromFileExtension[last.split('.').last];
  33. }
  34. }
  35. } else {
  36. mimeType = 'text/html';
  37. }
  38. ctx.response = ByteResponse(body: body, mimeType: mimeType);
  39. }, pathRegEx: pathRegEx, responseProcessor: responseProcessor);
  40. if (stripPrefix) skipCount = route.pathSegments.length - 1;
  41. return route;
  42. }