如何在 Flutter 中添加图片

How to add image in Flutter

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

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

我试过的:

 assets:
    - images/lake.jpg

里面 pubspec.ymal :

完整文件:

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 中进行干净重建,因为我找不到任何选项..

如有任何帮助,我们将不胜感激。

谢谢!

我认为错误是由冗余引起的,

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 支持,如果您将资产放在其他地方则不会获得这些支持。

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

uses-material-design: true,

如何在您的应用中包含图片

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

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

2。将您的图像添加到新文件夹

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

3。在 pubspec.yaml

中注册资产文件夹
  • 打开项目根目录中的 pubspec.yaml 文件。

  • assets 小节添加到 flutter 部分,如下所示:

      flutter:
        assets:
          - assets/images/lake.jpg
    
  • 如果您有多个要包含的图像,那么您可以省略文件名而只使用目录名(包括最后的 /):

      flutter:
        assets:
          - assets/images/
    

4。在代码中使用图片

  • 使用 Image.asset('assets/images/lake.jpg') 在图像小部件中获取资产。

  • 整个 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 进行更改时,我发现我经常需要完全停止我的应用程序并重新启动它,尤其是在添加资产时。否则我会崩溃。

运行 应用现在应该是这样的:

进一步阅读

  • 请参阅 documentation 了解如何为不同的密度提供备用图像。

视频

此处的第一个视频详细介绍了如何在您的应用中包含图像。第二个视频详细介绍了如何调整它们的外观。

将图像放入您的应用程序的另一种方法 (对我来说就是这样):

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

2 - 将图像添加到新文件夹

3 - 在 pubspec.yaml

中注册资产文件夹

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
      ),
    );
  }
}

他们不需要创建资产目录和图像目录,然后你把图像。 更好的方法是在 pubspec.yaml 存在的项目中创建图像目录并将图像放入其中 并访问该图像,就像 tutorial/documention

中所示

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

里面

当您在 pubspec.yaml 文件中添加资产目录时,请更加注意空格

这是错误的

flutter:
   assets:
    - assets/images/lake.jpg

这是正确的方法,

flutter:
  assets:
    - assets/images/
  1. 在项目的根目录中创建 images 文件夹。

  2. 将你的图片放到这个文件夹中,它应该看起来像

  3. 转到您的 pubspec.yaml 文件,添加 assets header 并密切注意所有空格。

    flutter:
    
      uses-material-design: true
    
      # add this
      assets:
        - images/profile.jpg
    
  4. 点击 IDE 右上角的 Packages get

  5. 现在您可以使用

    在任何地方使用您的图像
    Image.asset("images/profile.jpg")
    

创建与 lib 级别相同的资产目录

像这样

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

然后你的 pubspec.yaml 喜欢

  flutter:
  assets:
    - assets/images/

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

在Flutter中使用图像。执行这些步骤。

1. 在名为 images 的资产文件夹中创建一个 Directory 。如下图

2.将您想要的图片放入图片文件夹。

3. 打开 pubpsec.yaml 文件。并添加声明您的 images.Like:--

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,
          ),
          );

如果图像在包依赖项中,您还应该提供包名称,如果您从相同的依赖项引用图像的话!

Image.asset("assets/pics/events_empty.png", package: "ui_elements"),

参考: Asset images in package dependencies

--> 按照以下步骤操作 一个或多个 图片插入。:

-> 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. ••

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

完成☻♥

逗号位于下一行末尾时出错

uses-material-design: true,

assets: 缩进后的行不正确时,它会抛出以下错误

如果如下所示更正缩进,则错误已修复。

如果未添加资产文件,则会突出显示黄色背景,但Pub get不会抛出错误,但在安装过程中会出现错误。

简而言之,代码缩进和语法很重要

您可以创建一个文件夹并参考它,如图所示

您可以使用它来查看对资产内所有内容的访问,因为可能有图像、徽标、图标等文件夹...

在项目的根目录中创建资产文件夹

MyProject
    android
    assets
    ios
    lib
    test
    web
    windows
    .gitignore
    pubspec.yaml

在你的pubspec.yaml中,有

assets:
#   - images/a_dot_burr.jpeg
#  - images/a_dot_ham.jpeg

将最后两行替换为 'assets/' 以便能够直接访问资产中的所有内容

  • 如果您在资源中有直接图片

    assets:
      - assets/
    
  • 或者如果您在资产中有子文件夹

    assets:
      - assets/folder1/
      - assets/folder2/
      - assets/folder3/
    

确保在主目录中创建资产文件夹,而不是在 lib 文件夹中 enter image description here