web - 我在将图像添加到 flutter 项目时遇到问题

标签 web flutter dart

我正在试验一个 flutter web 项目(可能没有什么不同,但值得一提),我想添加一张图片,但每次尝试都会出错,

我已将正确的 Assets 添加到 pubspec.yaml 文件中,文件位于文件夹中。

我已经尝试重新启动我的 ide,并且 flutter clean。 完全没有变化。

class _homePageState extends State<homePage> {
  @override
  Widget build(BuildContext context) {
    var textStyle = TextStyle(
                    color: Colors.black,
                    fontSize: 30,
                    fontWeight: FontWeight.w100,
                );
                
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        fontFamily: "MontSerrat"
      ),

      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.grey[400],
          title: Text("Example",
            style: TextStyle(
              color: Colors.black,
              fontSize: 40,
              fontWeight: FontWeight.w100,
            ),
          )
        ),
        body: 
        Container(
          color: Colors.grey[400],
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image.asset('assets/images/first_image.jpg')
            ],
          ),
        )
      ),
    );
  }
}

pubspec.yaml 看起来像:

name: epq_webapp
description: An app built using Flutter for web

environment:
  # You must be using Flutter >=1.5.0 or Dart >=2.3.0
  sdk: '>=2.3.0-dev.0.1 <3.0.0'

dependencies:
  flutter_web: any
  flutter_web_ui: any

dev_dependencies:
  build_runner: ^1.4.0
  build_web_compilers: ^2.0.0
  pedantic: ^1.0.0

dependency_overrides:
  flutter_web:
    git:
      url: https://github.com/flutter/flutter_web
      path: packages/flutter_web
  flutter_web_ui:
    git:
      url: https://github.com/flutter/flutter_web
      path: packages/flutter_web_ui

flutter:
  fonts:
  - family: MontSerrat
    fonts:
      - asset: assets\fonts\montserrat\Montserrat-Regular.ttf

  assets:
    - assets/
    - assets/images/first_image.jpg

我希望我的代码能够显示图像,但是我收到一条错误消息,

无法加载资源:assets/images/first_image.jpg

最佳答案

Flutter 使用位于项目根目录的 pubspec.yaml 文件来识别应用程序所需的 Assets 。

flutter:
  assets:
    - assets/my_icon.png
    - assets/background.png

确保你的图像在 Assets 目录中

然后

Widget build(BuildContext context) {
  // ...
  return DecoratedBox(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('assets/background.png'),
        // ...
      ),
      // ...
    ),
  );
  // 
}

你应该渲染你的图像

关于web - 我在将图像添加到 flutter 项目时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56501045/

相关文章:

javascript - Dart 和第三方 CSS 和 JS 框架

dart - 动态实例化,添加聚合物元素 Dart

python - 通过 Python 访问响应头位置

python - Django 绝对 url 有效,但相对 url 不适用于静态文件

PHP PHPSESSID 利用困惑

flutter - 导入问题:日期格式 flutter

html - 为什么我的网页不能显示背景音乐?

dart - 将参数传递给 initState

gradle - flutter 运行失败 : A problem occurred configuring project ':shared_preferences'

string - 如何在 Dart 中连接两个字符串?