【问题标题】:How to add image in Flutter如何在 Flutter 中添加图片
【发布时间】:2018-11-26 22:10:48
【问题描述】:

我是第一次开发 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 dart flutter-layout


【解决方案1】:

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

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 文件。

  • 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,了解如何为不同密度提供替代图像。

视频

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

【讨论】:

    【解决方案2】:

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

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

    完成。☻♥

    【讨论】:

      【解决方案3】:

      逗号在下一行末尾时出错

      uses-material-design: true,
      

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

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

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

      总之,代码缩进和语法很重要

      您可以创建一个文件夹并如图所示引用它

      【讨论】:

        【解决方案4】:

        如果图像在包依赖项中,您还应该提供包名,如果您从同一依赖项引用图像,则事件!

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

        参考: Asset images in package dependencies

        【讨论】:

          【解决方案5】:

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

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

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

          3. 打开 pubpsec.yaml 文件。并添加声明你的图片。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,
                    ),
                    );
          

          【讨论】:

            【解决方案6】:

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

            喜欢这个

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

            然后你的 pubspec.yaml 就像

              flutter:
              assets:
                - assets/images/
            

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

            【讨论】:

              【解决方案7】:
              1. 在项目的根目录中创建images 文件夹。

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

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

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

              5. 现在您可以在任何地方使用您的图像

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

              【讨论】:

                【解决方案8】:

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

                这是错误的

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

                这是正确的方法,

                flutter:
                  assets:
                    - assets/images/
                

                【讨论】:

                • 哇!在尝试您的答案之前,我遇到了错误。魔鬼确实在细节中。非常感谢!
                【解决方案9】:

                他们不需要创建资产目录并在它的图像目录下,然后你把图像。 更好的方法是在 pubspec.yaml 所在的项目中创建 Images 目录并将图像放入其中 并像教程/文档中所示访问该图像

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

                【讨论】:

                  【解决方案10】:

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

                  1 - 创建资产/图像文件夹

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

                  【讨论】:

                    【解决方案11】:

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

                    uses-material-design: true,
                    

                    【讨论】:

                    • 还要确保 assets: 与 uses-material-design 保持一致
                    【解决方案12】:

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

                    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 支持,如果您将资产放在其他位置,您将无法获得这些支持。

                    【讨论】:

                    • 谢谢先生的回复。我已经创建了 assets 目录,并在该目录中创建了图像目录,并在其中删除了一个图像。也删除了 "," .. 但现在出现此错误 No file or variants found for asset: images/lake.jpg.
                    • 你还需要将assets目录添加到文件路径asset: assets/images/lake.jpg
                    • 先生,我还有一个查询.. 因为我在 main.dart 中做了一个演示并成功完成了它.. 现在我通过删除以前的代码在同一个文件中制作另一个演示.. 我得到了该新演示的输出,但现在当我从 apk 检查应用程序时,它显示的是第一个演示而不是当前演示。我做错了什么吗?
                    • 您可能需要运行 flutter clean 以使 flutter runflutter build 接受更改。我认为 Flutter 团队已经意识到了这个问题,并且它经常发生,但我不知道他们是否能很快解决它。
                    • 你需要在你的 Flutter 项目目录(pubspec.yaml 所在的位置)的命令行 shell 中执行它
                    猜你喜欢
                    • 2023-01-18
                    • 2020-07-09
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2021-11-28
                    • 2020-12-13
                    • 1970-01-01
                    相关资源
                    最近更新 更多