在flutter app中添加图片

Ann*_*nie 33 dart flutter flutter-layout

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

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

我尝试了什么:

 assets:
    - images/lake.jpg
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

错误日志:

#/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
Run Code Online (Sandbox Code Playgroud)

我的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,
          ],
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

任何帮助,将不胜感激.

谢谢 !

Sur*_*gch 65

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

对于未来的观众来说,这是一个更普遍的答案.

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

  • 它应位于项目的根目录中,与文件位于同一文件夹中pubspec.yaml.
  • 在Android Studio中,您可以在"项目"视图中单击鼠标右键
  • 你不必打电话assetsimages.你甚至不需要制作images一个子文件夹.但是,无论您使用什么名称,都将在pubspec.yaml文件中重复使用.

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

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

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

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
          ),
        );
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)

5.重新启动您的应用

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

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

在此输入图像描述

进一步阅读

  • 请参阅文档,了解如何为不同密度提供备用图像.


Gün*_*uer 25

我认为错误是由冗余造成的 ,

flutter:
  uses-material-design: true, # <<< redundant , at the end of the line
  assets:
    - images/lake.jpg
Run Code Online (Sandbox Code Playgroud)

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

flutter:
  uses-material-design: true
  assets:
    - assets/images/lake.jpg
Run Code Online (Sandbox Code Playgroud)

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


Cop*_*oad 12

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

    在此处输入图片说明

    在此处输入图片说明

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

    在此处输入图片说明

  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
    
    Run Code Online (Sandbox Code Playgroud)
  4. Tap on Packages get at the top right corner of the IDE.

    在此处输入图片说明

  5. Now you can use your image anywhere using

    Image.asset("images/profile.jpg")
    
    Run Code Online (Sandbox Code Playgroud)


小智 9

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

像这样

projectName
 -android
 -ios
 -lib
 -assets
 -pubspec.yaml
Run Code Online (Sandbox Code Playgroud)

那么你的 pubspec.yaml 就像

  flutter:
  assets:
    - assets/images/
Run Code Online (Sandbox Code Playgroud)

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


Fel*_*hes 8

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

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
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

爬上你的山!


Rao*_*che 7

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

uses-material-design: true,
Run Code Online (Sandbox Code Playgroud)


Nik*_*the 7

请按照以下步骤插入 一张或多张图像:

\n
-> Create \'assets/images\' folder as in project module.\n-> put images which you want.\n-> use of image using this syntax. ex.\n            - Image.asset(\'assets/images/tony.jpg\')\n\n-> use image avatar which you want like, circle, square and much more as your need.\n-> Open \'pubspec.yaml\' file\n-> write the code in \'flutter:\' section. ex.\n   -------------------------------\n   uses-material-design: true\n   assets:\n    - assets/images/             // if multiple images you have then\n    - assets/images/imagename.extension     // if single images you have then\n   -------------------------------\n-> click on \'PUB GET\' button which occurs on Right side of Screen above.\n-> Run App.\n-> if you get any issue then \n-> Go to file -> Invalid caches/Restart -> Invalid Caches/Restart button\n-> Done.\n
Run Code Online (Sandbox Code Playgroud)\n

请参阅下图以更好地了解实施方式。

\n
   \xe2\x80\xa2\xe2\x80\xa2 Here, add image file like below. \xe2\x80\xa2\xe2\x80\xa2\n
Run Code Online (Sandbox Code Playgroud)\n

在此输入图像描述

\n
   \xe2\x80\xa2\xe2\x80\xa2 Here, add image file Description in PUBSPEC.YAML file like below. \xe2\x80\xa2\xe2\x80\xa2\n
Run Code Online (Sandbox Code Playgroud)\n

在此输入图像描述

\n


mad*_*ddy 6

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

这是错误的

flutter:
   assets:
    - assets/images/lake.jpg
Run Code Online (Sandbox Code Playgroud)

这才是正确的做法

flutter:
  assets:
    - assets/images/
Run Code Online (Sandbox Code Playgroud)


Che*_*war 5

他们不需要创建 asset 目录并在其下创建 images 目录,然后将 image. 更好的方法是在存在 pubspec.yaml 的项目中创建 Images 目录,并将图像放入其中并访问该图像,就像教程/文档中所示

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


Rah*_*aha 5

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

1.创建一个目录内的文件夹命名为资产图像。如下图所示在此处输入图片说明

2.把你想要的图片放到图片文件夹中。

3.打开pubpsec.yaml文件。并添加声明您的图像。喜欢:--在此处输入图片说明

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,
          ),
          );
Run Code Online (Sandbox Code Playgroud)