dart - Server response with output from Future Object
问题描述
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'));
}
解决方案
分析仪为您的_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'});
}
推荐阅读
- asp.net-mvc - UserManager.UpdateSecurityStamp reverts user data
- java - 我如何遍历对象的 LinkedHashSet?
- php - if else 怎么写
- jenkins - 如何重启在windows机器上运行的jenkins
- c++ - C++ 获得“第二个命令行参数”
- sql - 我想按列显示列值组的总和。如何显示?
- visual-studio-code - Search selected text in all workspace files without having to hit the enter key to actually start the search?
- javafx - JavaFXML 创建新场景
- git - Yocto throws a git Fatal Error "Please tell me who you are" after after successful Bitbake build
- android - 当外部库中抛出异常时,Android Studio 挂起