0

Hola tengo un proyecto flutter donde puedo hacer que las imagen me carguen de un Image.network. Este es mi main.dart.

class ShowCase extends StatelessWidget {
const ShowCase({
@required this.wideImage,
@required this.bookObject,
});

final String wideImage;
final Book bookObject;

@override
Widget build(BuildContext context) {
return GestureDetector(
  onTap: () {
    Navigator.push(context,
        MaterialPageRoute(builder: (context) => Details(bookObject)));
  },
  child: Row(
    children: <Widget>[
      Container(
        height: 250,
        width: 350,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(10),
          child: Image.network(wideImage, fit: BoxFit.cover),
        ),
      ),
      SizedBox(
        width: 20,
      )
    ],
  ),
);
}
}

class HotList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
  decoration: BoxDecoration(
      gradient: LinearGradient(
        begin: Alignment.bottomCenter,
        end: Alignment.topCenter,
        colors: [Color(0xfff8f8f8), Colors.white],
      ),
      border:
          Border(bottom: BorderSide(color: Color(0xfff0f0f0), width: 2))),
  padding: EdgeInsets.only(left: 20, right: 20, top: 35, bottom: 15),
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Padding(
        padding: EdgeInsets.only(bottom: 20.0),
        child: Text(
          "Locomotor",
          style: TextStyle(
              color: Colors.black,
              fontSize: 30,
              fontWeight: FontWeight.w600),
        ),
      ),
      Container(
        height: 320,
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: booklist.books.length,
          itemBuilder: (BuildContext context, int i) {
            String title = booklist.books[i].title.length > 17
                ? booklist.books[i].title.substring(0, 15) + "..."
                : booklist.books[i].title;

            if (booklist.books[i].franchise) {
              return Container();
            } else {
              return ShowBooks(
                bookCoverImg: booklist.books[i].cover,
                price: booklist.books[i].price,
                author: booklist.books[i].author,
                title: title,
                bookObject: booklist.books[i],
              );
            }
          },
        ),
      )
    ],
  ),
);
}
}

Este es mi book.dart donde coloque el link de internet donde se aloja la imagen.

BookList booklist = BookList(books: [
Book(
  title: "Planos anatómicos",
  cover:
      "https://upload.wikimedia.org/wikipedia/en/a/a9/Harry_Potter_and_the_Deathly_Hallows.jpg",
  age: "ALL AGE",
  author: "J. K. Rowling",
  authorImg:
      "https://images.gr-assets.com/authors/1510435123p5/1077326.jpg",
  franchise: true,
  genre: "Locomotor",
  lanugage: "ENGLISH",
  rating: 4.5,
  price: 13.49,
  summary:
      "Without the guidance and protection of their professors, Harry (Daniel Radcliffe), Ron (Rupert Grint) and Hermione (Emma Watson) begin a mission to destroy the Horcruxes, the sources of Voldemort's immortality. Though they must rely on one another more than ever, dark forces threaten to tear them apart. Voldemort's Death Eaters have seized control of the Ministry of Magic and Hogwarts, and they are searching for Harry -- even as he and his friends prepare for the ultimate showdown.",
  wideImage: "https://wallpaperplay.com/walls/full/9/a/9/64844.jpg"),

Book(
  title: "A Song Of Ice And Fire",
  cover:
      "https://upload.wikimedia.org/wikipedia/en/thumb/d/dc/A_Song_of_Ice_and_Fire_book_collection_box_set_cover.jpg/220px-A_Song_of_Ice_and_Fire_book_collection_box_set_cover.jpg",
  age: "ABOVE 18",
  author: "George R. R. Martin",
  authorImg:
      "https://www.biography.com/.image/t_share/MTQ4NDc2MTkxNTY3NzgzMTE1/george_rr_martin_photo_mark_davis_wireimage_via_getty_images_164117282_resized.jpg",
  franchise: true,
  genre: "Sci-Fi",
  lanugage: "ENGLISH",
  price: 27.34,
  rating: 4.4,
  summary:
      "Game of Thrones is roughly based on the storylines of A Song of Ice and Fire, set in the fictional Seven Kingdoms of Westeros and the continent of Essos. The series chronicles the violent dynastic struggles among the realm's noble families for the Iron Throne, while other families fight for independence from it.",
  wideImage:
      "https://images-na.ssl-images-amazon.com/images/I/91KwasehsHL._RI_.jpg"),

class Book {
String title;

double price;
String cover;
String author;
Book(
  {@required this.title,
  @required this.price,

  });
}

Lo que quiera es que la imagen (por ejemplo la de "authoImage" me cargue desde la carpeta assets. osea quisiera que la imagen no se cargara desde internet, sino desde mi carpeta assets donde ya coloqué algunas imágenes. Como podria hacerlo? ya agregue la image asset en el pub spec.yaml ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... .....

2
  • Probaste usando Image.assets en lugar de Image network? Y tendrias que poner la ruta de tu directorio local el 23 feb. 2020 a las 15:17
  • Si. coloque en el Main.dart- child:ClipRect...child:Image.asset(bookCoverImg,).... luego en el Book.dart- Book( title: "Medula espinal", cover: "assets/evane.jpg",... pero no me aparece nada (el nombre de la imagen es "evane.jpg") o como deberia llamar a la imagen desde el book. çdart?? porque hasta ahora la llamo como "assets/evane.jpg" porque ese supongo que es su directorio o falta alguna palabra? el 23 feb. 2020 a las 15:32

1 respuesta 1

0

Al declarar la imagen en tu pubspect.yaml es super importante tener cuidado con la indentacion, puede que ese sea el problema, de cualquier manera te muestro el proceso para que no quede ninguna duda, sobre como agregar y utilizar imágenes:

Es bueno que tengamos claro que flutter no trae por defecto un archivo "assest", por lo tanto debemos crear uno en la raíz de nuestro proyecto, y agregar a este archivo los elementos que vamos a utilizar en este caso imágenes.

Luego tenemos que dirigirnos al pubspec.yaml, el cual se encuentra en la raíz del proyecto para intensificar los recursos que requiere la app, seria de la siguiente manera.

flutter:
  uses-material-design: true

  # Para agregar recursos(assets) a su aplicación, agregue una sección de recursos, como esta:
  assets:
    - assets/loro.png

Por ultimo, ya podrías utilizar tu imagen, por ejemplo:

Widget build(BuildContext context) {
  return Image(image: AssetImage('assets/loro.png'));
}

Nota: Al no colocar de manera correcta la indentacion, posible que recibas el siguiente error.

Error detected in pubspec.yaml:
Error on line 44, column 4: Expected a key while parsing a block mapping.
   ╷
44 │    assets:
   │    ^
   ╵
Please correct the pubspec.yaml file at /Users/haniel/Documents/development/work/example/pubspec.yaml
exit code 1

Mas información en flutter-es.io

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.