是否可以使用基于 Flutter 桌面的应用程序在本地环境中托管 Flutter Web 应用程序?
在谷歌上搜索这样的解决方案可能很困难,因为它涉及许多导致类似情况的关键字(当您需要本地解决方案时需要在线托管、仅命令行解决方案等)。
经过一番挖掘后,我最终使用了shelf https://pub.dev/packages/shelf包以在本地网络上部署我自己的 Flutter Web 应用程序。我只为 Windows 开发了这个,所以我不能保证它也能在其他平台上工作。
首先要做的显然是添加shelf
包在你的pubspec.yaml
: 之后我的就是这样了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。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)