You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter本地服务器部署:无法加载lib目录文件的问题求助

解决Flutter本地服务器无法访问lib目录文件的问题

问题分析

lib目录下的文件属于Flutter项目的内部资源,编译后会被打包到应用程序内部,并非暴露在可直接通过HTTP请求访问的文件系统路径中,所以HTML里直接引用文件名会加载失败。

解决方案

1. 调整资源存放位置并配置pubspec.yaml

  • 在项目根目录创建assets文件夹,将需要通过HTTP访问的文件(比如你的WW.png)移入该文件夹
  • 修改pubspec.yaml,添加资源配置,确保Flutter能识别这些资源:
flutter:
  assets:
    - assets/WW.png

2. 修改服务器代码,处理资源请求

需要在服务器中区分HTML页面请求和资源文件请求,通过Flutter的rootBundle读取assets资源并返回给客户端。修改后的代码如下:

import 'package:flutter/services.dart' show rootBundle;

startServer() async {
  var server = await HttpServer.bind(wifiIp, 8080);
  print("Server running on IP : " +
      server.address.toString() +
      " On Port : " +
      server.port.toString());
  
  await for (var request in server) {
    // 处理主页HTML请求
    if (request.uri.path == '/') {
      request.response
        ..headers.contentType = ContentType("text", "html", charset: "utf-8")
        ..write('<h1>Hello World<h1><br><br> <img src="/WW.png" alt="Cannot load file">')
        ..close();
    } 
    // 处理图片资源请求
    else if (request.uri.path == '/WW.png') {
      try {
        final bytes = await rootBundle.load('assets/WW.png');
        request.response
          ..headers.contentType = ContentType("image", "png")
          ..add(bytes.buffer.asUint8List())
          ..close();
      } catch (e) {
        request.response.statusCode = 404;
        request.response.close();
      }
    } 
    // 处理其他不存在的请求
    else {
      request.response.statusCode = 404;
      request.response.close();
    }
  }
}

3. 视频文件的适配方案

如果是用户选择的设备本地视频,不要放到assets目录,而是直接获取视频的本地文件路径。处理请求时,通过File类读取文件内容并返回,同时设置正确的ContentType(比如video/mp4):

import 'dart:io';

// 假设videoPath是用户选择的视频本地路径
else if (request.uri.path == '/video') {
  try {
    final file = File(videoPath);
    if (await file.exists()) {
      request.response
        ..headers.contentType = ContentType("video", "mp4")
        ..addStream(file.openRead())
        ..close();
    } else {
      request.response.statusCode = 404;
      request.response.close();
    }
  } catch (e) {
    request.response.statusCode = 500;
    request.response.close();
  }
}

核心要点

  • Flutter的assets资源无法通过文件系统路径直接访问,必须使用rootBundle读取
  • 本地服务器需要根据请求路径,返回对应资源的字节流和正确的Content-Type,客户端才能正常加载

内容的提问来源于stack exchange,提问作者Code With Raiju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 10:15:47