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

Visual Studio Code中Flutter项目无法导入Roboto Slab字体

Flutter导入Roboto Slab字体失败的排查与解决

问题核心原因

你当前的问题主要出在字体文件存放路径错误以及目录拼写不一致:

  • 你将字体放在了lib/fonts/Robo_Slab,但Flutter自定义字体应存放在项目根目录下的fonts文件夹,而非lib目录内
  • 目录名Robo_Slab和pubspec中配置的Roboto_Slab拼写不匹配,导致路径无法正确识别

分步解决步骤

1. 调整字体文件位置

将字体文件夹从lib/fonts/Robo_Slab移动到项目根目录下,创建fonts/Roboto_Slab目录(统一拼写),把RobotoSlab-VariableFont_wght.ttf放入其中,最终路径应为:

项目根目录/fonts/Roboto_Slab/RobotoSlab-VariableFont_wght.ttf

2. 修正pubspec.yaml配置

确保字体配置的缩进层级正确,路径与实际文件位置完全匹配,修正后的配置片段:

flutter:
  uses-material-design: true
  fonts:
    - family: RobotoSlab
      fonts:
        - asset: fonts/Roboto_Slab/RobotoSlab-VariableFont_wght.ttf

3. 刷新依赖并重启项目

  • 在终端执行命令:flutter pub get
  • 完全关闭并重启VS Code,同时重启Flutter应用,避免缓存导致配置不生效

验证代码

你的HomeScreen代码本身无问题,只需确保Text组件的fontFamily值与pubspec中配置的family字段一致即可:

import 'package:flutter/material.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AppBar Title',
          style: TextStyle(
            fontFamily: 'RobotoSlab'
          ),
        ),
        actions: [
          IconButton(
            onPressed: () {}, 
            icon: const Icon(Icons.search)
          ),
          IconButton(
            onPressed: () {},
            icon: const Icon(Icons.more_vert)
          )
        ],
      )
      
    );
  }
}

内容的提问来源于stack exchange,提问作者John Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:50:24