Подтвердить что ты не робот

Как добавить изображение в 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/

Также я хочу спросить, есть ли какие-либо инструменты для чистой перестройки во флаттере, поскольку я не могу найти какие-либо варианты для этого..

Любая помощь будет оценена.

Спасибо !

4b9b3361

Ответ 1

Я думаю, что ошибка вызвана избыточным ,

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

Как включить изображения в ваше приложение

1. Создайте папку assets/images

  • Он должен находиться в корне вашего проекта, в той же папке, что и ваш файл pubspec.yaml.
  • В Android Studio вы можете щелкнуть правой кнопкой мыши в представлении проекта
  • Вам не нужно называть это assets или images. Вам даже не нужно делать 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 с 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

дальнейшее чтение

  • См. Документацию о том, как сделать альтернативные изображения для разных плотностей.

Ответ 3

  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. Нажмите на Packages get в верхнем правом углу IDE.

    enter image description here

  5. Теперь вы можете использовать свое изображение в любом месте, используя

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

Ответ 4

Проблема в вашем pubspec.yaml, здесь вам нужно удалить последнюю запятую.

uses-material-design: true,

Ответ 5

Альтернативный способ размещения изображений в вашем приложении (для меня это просто работает):

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!

Ответ 6

Их не нужно создавать каталог ресурсов и под ним каталог изображений, а затем вы помещаете изображение. Лучше просто создать каталог Images внутри вашего проекта, в котором существует pubspec.yaml, и поместить в него изображения и получить к ним доступ, как показано в руководстве/документации.

assets: - images/lake.jpg//внутри pubspec.yaml

Ответ 7

При добавлении каталога ресурсов в файл pubspec.yaml больше внимания уделяйте пробелам

это не верно

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

Это правильный путь,

flutter:
  assets:
    - assets/images/