flutter运行web报错failed to load font roboto如何解决

在Flutter项目中运行Web版本时遇到错误"Failed to load font Roboto",控制台显示字体加载失败。尝试过清理缓存和重新安装依赖,但问题依然存在。请问如何解决这个字体加载问题?是否需要手动配置字体或检查网络权限?

2 回复

pubspec.yaml 中添加依赖:

dependencies:
  google_fonts: ^2.1.0

然后运行 flutter pub get 即可解决。

更多关于flutter运行web报错failed to load font roboto如何解决的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter Web中遇到"failed to load font Roboto"错误,通常是因为字体加载失败。以下是几种解决方案:

解决方案

1. 检查网络连接和防火墙

确保网络连接正常,没有被防火墙或代理阻止字体下载。

2. 修改 pubspec.yaml 配置

flutter:
  uses-material-design: true
  fonts:
    - family: Roboto
      fonts:
        - asset: fonts/Roboto-Regular.ttf
        - asset: fonts/Roboto-Bold.ttf
          weight: 700

3. 本地导入Roboto字体

  1. 下载Roboto字体文件(从Google Fonts)
  2. 在项目根目录创建 fonts 文件夹
  3. 将字体文件放入 fonts 文件夹
  4. pubspec.yaml 中添加上述配置
  5. 运行 flutter pub get

4. 使用CDN字体(推荐)

web/index.html<head> 中添加:

<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">

5. 禁用Material Design字体

如果不需要Roboto字体,可以在 main.dart 中:

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        fontFamily: 'Arial', // 使用系统字体替代
      ),
      home: MyHomePage(),
    );
  }
}

6. 清理和重新构建

flutter clean
flutter pub get
flutter run -d chrome

推荐做法

建议使用第4种方案(CDN字体),因为:

  • 无需本地存储字体文件
  • 加载速度较快
  • 兼容性更好

选择最适合你项目需求的解决方案即可解决此问题。

回到顶部