0

i created a async/await function in another file thus its handler is returning a Future Object. Now i can't understand how to give response to client with content of that Future Object in Dart. I am using basic dart server with shelf package.Below is code where ht.handler('list') returns a Future Object and i want to send that string to client as response. But i am getting internal server error.

import 'dart:io';

import 'package:args/args.dart';
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
import 'HallTicket.dart' as ht;

// For Google Cloud Run, set _hostname to '0.0.0.0'.
const _hostname = 'localhost';

main(List<String> args) async {
  var parser = ArgParser()..addOption('port', abbr: 'p');
  var result = parser.parse(args);

  // For Google Cloud Run, we respect the PORT environment variable
  var portStr = result['port'] ?? Platform.environment['PORT'] ?? '8080';
  var port = int.tryParse(portStr);

  if (port == null) {
    stdout.writeln('Could not parse port value "$portStr" into a number.');
    // 64: command line usage error
    exitCode = 64;
    return;
  }

  var handler = const shelf.Pipeline()
      .addMiddleware(shelf.logRequests())
      .addHandler(_echoRequest);

  var server = await io.serve(handler, _hostname, port);
  print('Serving at http://${server.address.host}:${server.port}');
}

Future<shelf.Response> _echoRequest(shelf.Request request)async{
    shelf.Response.ok('Request for "${request.url}"\n'+await ht.handler('list'));
}
4

1 回答 1

0

分析仪为您的_echoRequest方法提供以下警告:

info:此函数的返回类型为“Future”,但不以 return 语句结束。

如果您检查要求,addHandler您会看到它期望返回一个处理程序。

所以你需要添加让它在我的机器上工作的返回:

Future<shelf.Response> _echoRequest(shelf.Request request) async {
  return shelf.Response.ok(
      'Request for "${request.url}"\n' + await ht.handler('list2'),
      headers: {'Content-Type': 'text/html'});
}
于 2019-11-28T14:04:10.730 回答