如何在Flutter中添加图片

185

我第一次开发Flutter应用程序,遇到添加图像的问题。我有以下问题:

  1. 在哪里创建图像文件夹?
  2. 在pubspec.ymal中添加资产标签的位置是哪里?
  3. 是否需要任何资产文件夹?

我尝试过:

 assets:
    - images/lake.jpg

在 pubspec.yaml 文件内:

完整文件:

name: my_flutter_app
description: A new Flutter application.

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true,
  assets:
    - images/lake.jpg

错误日志:

#/properties/flutter/properties/uses-material-design: type: wanted [boolean] got true,
Error detected in pubspec.yaml:
Error building assets

FAILURE: Build failed with an exception.

* Where:
Script '/home/abc/Downloads/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 435

* What went wrong:
Execution failed for task ':app:flutterBuildDebug'.
> Process 'command '/home/abc/Downloads/flutter/bin/flutter'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
Finished with error: Gradle build failed: 1

我的 main.dart 代码:

// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';
// Uncomment lines 7 and 10 to view the visual layout at runtime.
//import 'package:flutter/rendering.dart' show debugPaintSizeEnabled;

void main() {
  //debugPaintSizeEnabled = true;
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Widget titleSection = new Container(
      padding: const EdgeInsets.all(32.0),
      child: new Row(
        children: [
          new Expanded(
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                new Container(
                  padding: const EdgeInsets.only(bottom: 8.0),
                  child: new Text(
                    'Oeschinen Lake Campground',
                    style: new TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                new Text(
                  'Kandersteg, Switzerland',
                  style: new TextStyle(
                    color: Colors.grey[500],
                  ),
                ),
              ],
            ),
          ),
          new Icon(
            Icons.star,
            color: Colors.red[500],
          ),
          new Text('41'),
        ],
      ),
    );

    Column buildButtonColumn(IconData icon, String label) {
      Color color = Theme.of(context).primaryColor;

      return new Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          new Icon(icon, color: color),
          new Container(
            margin: const EdgeInsets.only(top: 8.0),
            child: new Text(
              label,
              style: new TextStyle(
                fontSize: 12.0,
                fontWeight: FontWeight.w400,
                color: color,
              ),
            ),
          ),
        ],
      );
    }

    Widget buttonSection = new Container(
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          buildButtonColumn(Icons.call, 'CALL'),
          buildButtonColumn(Icons.near_me, 'ROUTE'),
          buildButtonColumn(Icons.share, 'SHARE'),
        ],
      ),
    );

    Widget textSection = new Container(
      padding: const EdgeInsets.all(32.0),
      child: new Text(
        '''
Lake Oeschinen lies at the foot of the Blüemlisalp in the Bernese Alps. Situated 1,578 meters above sea level, it is one of the larger Alpine Lakes. A gondola ride from Kandersteg, followed by a half-hour walk through pastures and pine forest, leads you to the lake, which warms to 20 degrees Celsius in the summer. Activities enjoyed here include rowing, and riding the summer toboggan run.
        ''',
        softWrap: true,
      ),
    );

    return new MaterialApp(
      title: 'Flutter Demo',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Top Lakes'),
        ),
        body: new ListView(
          children: [
            new Image.asset(
              'images/lake.jpg',
              width: 600.0,
              height: 240.0,
              fit: BoxFit.cover,
            ),
            titleSection,
            buttonSection,
            textSection,
          ],
        ),
      ),
    );
  }
}

我指的是这个教程https://flutter.io/tutorials/layout/

另外,我想问一下在Flutter中是否有任何工具可以进行干净的重建,因为我找不到任何选项。


你的标题太泛泛而谈了,误导了很多人来到这里,包括我在内。考虑更改一下吗? - stackunderflow
请观看这个视频:https://youtu.be/70G_XbpEyYk - theprasunranjan
非常感谢官方文档 - 非常清晰!没有人不知道在哪里放置他们的图像。 - Georgiy Chebotarev
16个回答

327

如何在应用中添加图片

1. 创建一个assets/images文件夹

  • 该文件夹应该位于您的项目根目录中,与pubspec.yaml文件位于同一文件夹中。
  • 在Android Studio中,您可以右键单击项目视图
  • 您不必称之为assetsimages。您甚至不需要将images设置为子文件夹。但是,无论您使用什么名称,在pubspec.yaml文件中注册的就是它。

2. 将您的图片添加到新文件夹中

  • 您可以将图像直接复制到assets/images中。例如,lake.jpg的相对路径将是assets/images/lake.jpg

3. 在pubspec.yaml中注册assets文件夹

  • 打开位于项目根目录中的pubspec.yaml文件。
  • flutter部分中添加一个assets子部分,如下所示:
flutter:
  assets:
    - assets/images/lake.jpg
  • 如果您有多张图片需要包含,则可以省略文件名,只使用目录名称(包括最后的/):
flutter:
  assets:
    - assets/images/

Note: 确保使用 确切的 空格数量。每个缩进需要使用 2 个空格。

4. 在代码中使用图片

  • 使用 Image.asset('assets/images/lake.jpg') 将资源获取到一个 Image widget 中。
  • 整个 main.dart 文件在此处:
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Image from assets"),
        ),
        body: Image.asset('assets/images/lake.jpg'), //   <--- image
      ),
    );
  }
}

5. 重新启动你的应用

当我对 pubspec.yaml 进行更改时,我经常发现需要完全停止我的应用并重新启动它,尤其是在添加资源时。否则,我会遇到崩溃。

现在运行应用程序,你应该有类似这样的东西:

输入图像描述

进一步阅读

  • 查看文档以了解如何提供不同密度的替代图像等内容。

视频

这里的第一个视频详细介绍了如何在应用程序中包含图像。第二个视频涵盖了更多有关如何调整它们外观的内容。


94

我认为错误是由于多余的,引起的。

flutter:
  uses-material-design: true, # <<< redundant , at the end of the line
  assets:
    - images/lake.jpg

我建议在包含pubspec.yaml文件的目录中创建一个assets文件夹,将images移动到该文件夹中并使用。

flutter:
  uses-material-design: true
  assets:
    - assets/images/lake.jpg

assets 目录将获得一些额外的 IDE 支持,如果您把资产放在其他地方,则没有这些功能。


1
你仍然需要将 assets 目录添加到文件路径 asset: assets/images/lake.jpg 中。 - Günter Zöchbauer
1
你可能需要运行 flutter clean 命令来使得 flutter run 或者 flutter build 命令能够应用更改。我认为 Flutter 团队已经意识到了这个问题,而且它经常发生,但我无法确定他们是否能够很快修复它。 - Günter Zöchbauer
1
你需要在 Flutter 项目目录(即pubspec.yaml所在目录)中的命令行 shell 中执行它。 - Günter Zöchbauer
在代码中引用资源时自动完成,但是没有进展。 - Günter Zöchbauer
你指的是哪种自动完成?已经有自动完成了,而文件名是一个字符串,所以它不会被捕捉到。 - West
显示剩余5条评论

34
  1. Create images folder in root level of your project.

    enter image description here

    enter image description here

  2. Drop your image in this folder, it should look like

    enter image description here

  3. Go to your pubspec.yaml file, add assets header and pay close attention to all the spaces.

    flutter:
    
      uses-material-design: true
    
      # add this
      assets:
        - images/profile.jpg
    
  4. Tap on Packages get at the top right corner of the IDE.

    enter image description here

  5. Now you can use your image anywhere using

    Image.asset("images/profile.jpg")
    

12

在Flutter中使用图像。请按照以下步骤操作。

1. 在资产文件夹内创建名为images目录。如下图所示enter image description here

2. 将所需的图像放入图像文件夹中。

3. 打开pubspec.yaml文件,并声明您的图像。例如:--enter image description here

4. 在您的代码中使用这些图像。

  Card(
            elevation: 10,
              child: Container(
              decoration: BoxDecoration(
                color: Colors.orangeAccent,
              image: DecorationImage(
              image: AssetImage("assets/images/dropbox.png"),
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
          ),
          ),
          child: Text("$index",style: TextStyle(color: Colors.red,fontSize: 16,fontFamily:'LangerReguler')),
                alignment: Alignment.center,
          ),
          );

11

问题出在你的pubspec.yaml文件中,你需要删除最后一个逗号。

uses-material-design: true,

同时确保 assets: 与 uses-material-design 对齐。 - Swapnil Kadam

10

一种在应用程序中添加图片的替代方法(这种方法对我来说非常有效):

1 - 创建一个 assets/images 文件夹。

2 - 将您的图片添加到新文件夹中。

3 - 在 pubspec.yaml 中注册 assets 文件夹。

4 - 使用以下代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    var assetsImage = new AssetImage('assets/images/mountain.jpg'); //<- Creates an object that fetches an image.
    var image = new Image(image: assetsImage, fit: BoxFit.cover); //<- Creates a widget that displays an image.

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Climb your mountain!"),
          backgroundColor: Colors.amber[600], //<- background color to combine with the picture :-)
        ),
        body: Container(child: image), //<- place where the image appears
      ),
    );
  }
}

Climb your mountain!


9

将您的资源目录创建为与lib级别相同

像这样

projectName
 -android
 -ios
 -lib
 -assets
 -pubspec.yaml

那么你的 pubspec.yaml 应该像这样

  flutter:
  assets:
    - assets/images/

现在你可以使用 Image.asset("/assets/images/")


7

--> 请按照以下步骤 插入一个或多个图像:

-> Create 'assets/images' folder as in project module.
-> put images which you want.
-> use of image using this syntax. ex.
            - Image.asset('assets/images/tony.jpg')

-> use image avatar which you want like, circle, square and much more as your need.
-> Open 'pubspec.yaml' file
-> write the code in 'flutter:' section. ex.
   -------------------------------
   uses-material-design: true
   assets:
    - assets/images/             // if multiple images you have then
    - assets/images/imagename.extension     // if single images you have then
   -------------------------------
-> click on 'PUB GET' button which occurs on Right side of Screen above.
-> Run App.
-> if you get any issue then 
-> Go to file -> Invalid caches/Restart -> Invalid Caches/Restart button
-> Done.

请参考下面的图片,以更好地了解实现。
   •• Here, add image file like below. ••

enter image description here

   •• Here, add image file Description in PUBSPEC.YAML file like below. ••

enter image description here

Done.☻♥


6
在pubspec.yaml文件中添加assets目录时要注意空格。
这是错误的。
flutter:
   assets:
    - assets/images/lake.jpg

这是正确的方式,

flutter:
  assets:
    - assets/images/

哇!在尝试了你的答案之前我一直在遇到错误。细节真的很重要。非常感谢! - Emzor

5

不需要创建asset目录和其中的images目录,然后再放置图像。 最好在与pubspec.yaml文件同级别的项目中仅创建Images目录,并将图像放置在其中, 并像教程/文档中展示的那样访问这些图像。

资产: - images/lake.jpg // 在pubspec.yaml中


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接