仅使用Flutter在本地环境中托管Web服务器

hs1rzwqc  于 2022-12-14  发布在  Flutter
关注(0)|答案(1)|浏览(187)

是否可以使用Flutter桌面应用在本地环境中托管Flutter Web应用?

kgsdhlau

kgsdhlau1#

谷歌搜索这样的解决方案可能很困难,因为它涉及到许多关键词,导致类似的情况(在线托管时,你需要一个本地解决方案,命令行解决方案,等等)。
经过一番挖掘,我最终使用shelf包在本地网络上部署了我自己的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的更多详细信息,请参阅其www.example.com页面上的APIpub.dev。

相关问题