是否可以使用基于Flutter桌面的应用程序在本地环境中托管Flutter web应用程序?
在google上搜索这样的解决方案可能会很困难,因为它涉及许多导致类似情况的关键字(需要本地解决方案时的在线托管、仅命令行解决方案等)。
经过一番挖掘,我最终使用架子包在本地网络上部署我自己的Flutter web应用程序。我只针对Windows开发了这个程序,所以我不能保证它能在其他平台上运行。首先要做的显然是在pubspec.yaml
中添加shelf
包:之后,这就是我的main
方法看起来像
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf_router/shelf_router.dart' as shelf_router;
[...]
void main() async{
[...]
var secureContext = SecurityContext();
try {
//privKey and cert are the String names of the two files for the SSL connection,
//placed in the root directory of the flutter project or along with the .exe file (when released)
secureContext.usePrivateKey(privKey);
secureContext.useCertificateChain(cert);
} catch (error) {
logger.e("Error on init SecurityContext");
}
try {
//this is the handler that deploys the files contained in 'webAppFolder': I just simply pasted the result of
//the flutter webapp building inside (the index.html file is the default one for flutter web)
//and put the folder in the root of the flutter project (or, again, in the same folder with the .exe file when released)
final _staticHandler = createStaticHandler("webAppFolder", defaultDocument: 'index.html');
//this I kept just for a reminder on how to deploy a static page, if needed
final _router = shelf_router.Router()
..get(
'/time',
(request) => shelf.Response.ok(DateTime.now().toUtc().toIso8601String()),
);
final cascade = shelf.Cascade()
.add(_staticHandler)
.add(_router);
try {
var server = await shelf_io.serve(
cascade.handler,
InternetAddress.anyIPv4,
mainPort, //this is the number of the port on which the webapp is deployed (I load this from a .ini file beforehand
securityContext: secureContext,
);
// Enable content compression
server.autoCompress = true;
logger.i("Serving at https://${server.address.host}:${server.port}");
} catch (err) {
logger.e("Error while serving");
logger.e(err.toString());
}
} catch (err) {
logger.e("Error while creating handler");
logger.e(err.toString());
}
runApp(MaterialApp(
[...]
这是与web应用程序部署相关的部分:由于flutter桌面应用程序已经提供了GUI,因此我使用它添加了一些维护和测试实用程序,以检查是否一切正常。
有关shelf
的更多详细信息,请参阅其pub.dev页面上的API。