在flutter app中添加图片

时间:2018-06-18 05:28:53

标签: android dart flutter flutter-layout

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

  1. 在哪里创建图片文件夹?
  2. 在pubspec.ymal中添加资产标记的位置?
  3. 这需要资源文件夹吗?
  4. 我尝试了什么:

     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/

    另外我想问一下,有什么工具可以在颤动中进行干净的重建,因为我找不到任何选择..

    任何帮助都将不胜感激。

    谢谢!

11 个答案:

答案 0 :(得分:36)

如何在应用程序中包含图像

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());
    
    // the root widget of our application
    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 here
          ),
        );
      }
    }
    

5。重新启动您的应用

当对 pubspec.yaml 进行更改时,我经常需要完全停止我的应用程序并再次重新启动它,特别是在添加资产时。否则我会崩溃。

现在运行该应用程序,您应该具有以下内容:

enter image description here

进一步阅读

  • 有关如何进行操作(例如提供不同密度的备用图像)的信息,请参见documentation

答案 1 :(得分:16)

我认为错误是由多余的,

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

我还建议在包含assets文件的目录中创建一个pubspec.yaml文件夹,然后在其中移动images并使用

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

如果您将资产放在其他位置,assets目录将获得一些额外的IDE支持。

答案 2 :(得分:7)

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

像这样

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

然后像

这样的pubspec.yaml
  flutter:
  assets:
    - assets/images/

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

答案 3 :(得分:4)

问题出在pubspec.yaml,您需要删除最后一个逗号。

uses-material-design: true,

答案 4 :(得分:3)

在应用中放置图片的另一种方式 (对我来说,它就是这种方式):

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

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

Climb your mountain!

答案 5 :(得分:3)

它们无需创建资产目录,而是在其下创建images目录,然后放置image。 更好的方法是在存在pubspec.yaml的项目中创建Images目录,并将图像放入其中 并按照教程/文档中所示的方式访问这些图像

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

答案 6 :(得分:3)

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

1.在名为images的assets文件夹中创建一个目录。如下图所示enter image description here

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

3. 打开 pubpsec.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,
          ),
          );

答案 7 :(得分:1)

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

这是错误的

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

这是正确的方法,

flutter:
  assets:
    - assets/images/

答案 8 :(得分:1)

  1. 在项目的根级别创建images文件夹。

    enter image description here

    enter image description here

  2. 将图像拖放到该文件夹​​中,它的外观应类似于

    enter image description here

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

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

    enter image description here

  5. 现在,您可以使用

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

答案 9 :(得分:0)

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

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

参考: Asset images in package dependencies

答案 10 :(得分:0)

--> 按照以下步骤操作:

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

请参阅下面的图片以更好地了解实施。

assets/image path model

pubspec.yaml model