简体   繁体   中英

Images load by themselves, but not as a randomized list. - Flutter

and thank you in advance for any assistance.

So, I have images load properly when I use them within a container in other areas of the code, but I also want some of those images to display randomly within the AppBar.

Given that they do load in other locations within the code, I don't suspect a Pubyaml error.

I'm still fairly new to flutter, and lists in general. So I wouldn't be surprised if I messed up something with the list itself, or the way it's called.

It gives me this error:

Syncing files to device iPhone...
Reloaded 8 of 502 libraries in 411ms.

════════ Exception caught by image resource service ════════════════════════════════════════════════
The following assertion was thrown resolving an image codec:
Unable to load asset: Image(image: AssetImage(bundle: null, name: "images/Mem2.JPG"), frameBuilder: null, loadingBuilder: null, alignment: center, this.excludeFromSemantics: false, filterQuality: low)

When the exception was thrown, this was the stack: 
#0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
<asynchronous suspension>
#1      AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:484:44)
#2      AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:469:14)
#3      ImageProvider.resolve.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:327:17)
...
Image provider: AssetImage(bundle: null, name: "Image(image: AssetImage(bundle: null, name: "images/Mem2.JPG"), frameBuilder: null, loadingBuilder: null, alignment: center, this.excludeFromSemantics: false, filterQuality: low)")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#c99db(), name: "Image(image: AssetImage(bundle: null, name: "images/Mem2.JPG"), frameBuilder: null, loadingBuilder: null, alignment: center, this.excludeFromSemantics: false, filterQuality: low)", scale: 1.0)
════════════════════════════════════════════════════════════════════════════════════════════════════

Here's the code:

class ContactProfilePage extends StatefulWidget {
  @override
  _ContactProfilePageState createState() => _ContactProfilePageState();
}

class _ContactProfilePageState extends State<ContactProfilePage> {
  List<Attr> attr = [
    Attr(name: ''),
  ];

  dynamic randAppBarImg = [
    "images/Mem2.JPG",
    "images/Mem3.JPG",
    "images/Mem4.JPG",
    "images/Mem6.jpg",
    "images/memory - 1.jpeg",
    "images/memory - 2.jpeg",
    "images/memory - 3.jpeg",
    "images/memory - 4.jpeg",
    "images/memory - 5.jpeg",
    "images/memory - 6.jpeg",
  ];

  Random rnd;

  Image img() {
    int min = 0;
    int max = randAppBarImg.length - 1;
    rnd = Random();
    int r = min + rnd.nextInt(max - min);
    String image_name = randAppBarImg[r].toString();
    return Image.asset(image_name);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.lightBlueAccent,
        child: Icon(Icons.add),
        onPressed: () {
          //Modal sheet brings up the whole bottom pane when the plus button is pressed.
          showModalBottomSheet(
            context: context,
            builder: (context) => AddAttrScreen(
              (newAttrTitle) {
                setState(() {
                  //adds the Attr to the list anytime the user presses "Add"
                  attr.add(Attr(name: newAttrTitle));
                });
                Navigator.pop(context);
                //Hides the floating add Attr screen after pressing "Add"
              },
            ),
          );
          //TODO Change it so the categories don't have to be selected every time. Instead, have the add button WITHIN each category.
          // This floating button should instead create a new category.
        },
      ),
      drawer: DrawerMain(),
      body: NestedScrollView(
        //This allows for the top bar to collapse, while retaining the image.
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverAppBar(
              expandedHeight: 200.0,
              floating: true,
              snap: true,
              pinned: true,
              flexibleSpace: Stack(
                children: <Widget>[
                  Positioned.fill(
                      child: Image.asset(
                    img().toString(),
                    fit: BoxFit.cover,
                  ))
                ],
              ),
            ),
          ];
        },


        body: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Row(
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: CircleAvatar(
                        maxRadius: 50.0,
                        backgroundImage: AssetImage("images/fox.jpeg")),
                  ),
                  Container(
                    //TODO ADD ON PRESSED FUNCTION TO SOCIAL ICONS
                    margin: EdgeInsets.all(15.0),
                    child: Icon(
                      FontAwesomeIcons.facebook,
                      size: 40.0,
                      color: Color(0xFF306060),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.all(15.0),
                    child: Icon(
                      FontAwesomeIcons.instagram,
                      size: 40.0,
                      color: Color(0xFF306060),
                    ),
                  ),
                ],
              ),
              Padding(
                padding: const EdgeInsets.only(left: 15.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'Armando Pacheco Ortiz',
                      style: TextStyle(
                          fontSize: 25.0,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFF306060)),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 15.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'Freelance App Developer from Puerto Rico',
                      style: TextStyle(
                          fontSize: 20.0,
                          fontStyle: FontStyle.italic,
                          color: Color(0xFF306060)),
                    ),
                    SizedBox(
                      child: Divider(),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Row(
                  children: <Widget>[
                    Text('Memories',
                        style: TextStyle(
                            fontSize: 20.0,
                            fontStyle: FontStyle.italic,
                            color: Color(0xFF306060),
                            fontWeight: FontWeight.bold))
                  ],
                ),
              ),

              //Horizontal scrolling images.
              //TODO These need to update based on uploads, perhaps use something like google's face detection to auto add?
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      Container(
                        height: 310,
                        width: 200,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(20.0),
                          child: (Image.asset(
                            'images/Mem6.jpg',
                            fit: BoxFit.cover,
                          )),
                        ),
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      Container(
                        height: 310,
                        width: 200,
                        //ClipRRect allows for it to have the border radius. Container is painted behind the image.
                        //For that reason, adding a border radius to the container doesn't work.
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(20.0),
                          child: (Image.asset(
                            'images/Mem2.JPG',
                            fit: BoxFit.cover,
                          )),
                        ),
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      Container(
                        height: 310,
                        width: 200,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(20.0),
                          child: (Image.asset(
                            'images/memory - 4.jpeg',
                            fit: BoxFit.cover,
                          )),
                        ),
                      ),


I pasted the code as far down as the first image, to show how I have it set up in the other locations.

I'm not sure if the issue is with random images within the appBar, or maybe some code I'm missing. Hopefully, someone can shed some light on this!

Many thanks.

UPDATE:

So that helped a ton and definitely got things running! But I did notice two new problems cropping up.

  1. I had to rename all the images from: "memory - 6" to "Mem6", and that finally allowed them to show up. Otherwise, sometimes it would revert back to the default teal color, and not display anything, besides an error about not being able to load the asset again. I imagine it's just a naming error I was unknowingly causing?

  2. Scrolling down will cause the Appbar to "refresh" again, and randomize the pictures with the slightest scrolling until you stop. If I scroll back up, it'll do it again. It doesn't create an error, but it does crash the app eventually from so much refreshing I guess. How would I get around this? Is there an override, or should I simply create the widget with some Finals, or stateless/stateful widgets? I'm still learning the lingo and all that, so my apologies for the ignorance.

You can copy paste run full code below
Your img() has bug, you return an Image.asset and wrap in Image.asset again cause duplicate

Image.asset(
             img().toString(),
             fit: BoxFit.cover,
           ))

code snippet just return String of image_name will work
and do not include space in image name

String img() {
    int min = 0;
    int max = randAppBarImg.length - 1;
    rnd = Random();
    int r = min + rnd.nextInt(max - min);
    String image_name = randAppBarImg[r].toString();
    //return Image.asset(image_name);
    return image_name;
  }

working demo

在此处输入图片说明

full code

import 'package:flutter/material.dart';
import 'dart:math';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ContactProfilePage(),
    );
  }
}

class Attr {
  String name;
  Attr({this.name});
}

class ContactProfilePage extends StatefulWidget {
  @override
  _ContactProfilePageState createState() => _ContactProfilePageState();
}

class _ContactProfilePageState extends State<ContactProfilePage> {
  List<Attr> attr = [
    Attr(name: ''),
  ];

  dynamic randAppBarImg = [
    "images/Mem2.JPG",
    "images/Mem3.JPG",
    /*"images/Mem4.JPG",
    "images/Mem6.jpg",
    "images/memory-1.jpeg",
    "images/memory-2.jpeg",
    "images/memory-3.jpeg",
    "images/memory-4.jpeg",
    "images/memory-5.jpeg",
    "images/memory-6.jpeg",*/
  ];

  Random rnd;

  String img() {
    int min = 0;
    int max = randAppBarImg.length - 1;
    rnd = Random();
    int r = min + rnd.nextInt(max - min);
    String image_name = randAppBarImg[r].toString();
    //return Image.asset(image_name);
    return image_name;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(
          backgroundColor: Colors.lightBlueAccent,
          child: Icon(Icons.add),
          onPressed: () {
            //Modal sheet brings up the whole bottom pane when the plus button is pressed.
            /*       showModalBottomSheet(
              context: context,
              builder: (context) => AddAttrScreen(
                (newAttrTitle) {
                  setState(() {
                    //adds the Attr to the list anytime the user presses "Add"
                    attr.add(Attr(name: newAttrTitle));
                  });
                  Navigator.pop(context);
                  //Hides the floating add Attr screen after pressing "Add"
                },
              ),
            );*/
            //TODO Change it so the categories don't have to be selected every time. Instead, have the add button WITHIN each category.
            // This floating button should instead create a new category.
          },
        ),
        //drawer: DrawerMain(),
        body: NestedScrollView(
            //This allows for the top bar to collapse, while retaining the image.
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return <Widget>[
                SliverAppBar(
                  expandedHeight: 200.0,
                  floating: true,
                  snap: true,
                  pinned: true,
                  /*flexibleSpace: FlexibleSpaceBar(
                      centerTitle: true,
                      title: Text("",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.0,
                          )),
                      background: Image.asset(
                        "images/Mem2.JPG",
                        fit: BoxFit.cover,
                      )),*/
                  flexibleSpace: Stack(
                    children: <Widget>[
                      Positioned.fill(
                          child: Image.asset(
                        img().toString(),
                        fit: BoxFit.cover,
                      ))
                    ],
                  ),
                ),
              ];
            },
            body: SingleChildScrollView(
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.all(15.0),
                        child: CircleAvatar(
                            maxRadius: 50.0,
                            backgroundImage: AssetImage("images/fox.jpeg")),
                      ),
                      Container(
                        //TODO ADD ON PRESSED FUNCTION TO SOCIAL ICONS
                        margin: EdgeInsets.all(15.0),
                        child: Icon(
                          FontAwesomeIcons.facebook,
                          size: 40.0,
                          color: Color(0xFF306060),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.all(15.0),
                        child: Icon(
                          FontAwesomeIcons.instagram,
                          size: 40.0,
                          color: Color(0xFF306060),
                        ),
                      ),
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 15.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'Armando Pacheco Ortiz',
                          style: TextStyle(
                              fontSize: 25.0,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF306060)),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 15.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          'Freelance App Developer from Puerto Rico',
                          style: TextStyle(
                              fontSize: 20.0,
                              fontStyle: FontStyle.italic,
                              color: Color(0xFF306060)),
                        ),
                        SizedBox(
                          child: Divider(),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: Row(
                      children: <Widget>[
                        Text('Memories',
                            style: TextStyle(
                                fontSize: 20.0,
                                fontStyle: FontStyle.italic,
                                color: Color(0xFF306060),
                                fontWeight: FontWeight.bold))
                      ],
                    ),
                  ),

                  //Horizontal scrolling images.
                  //TODO These need to update based on uploads, perhaps use something like google's face detection to auto add?
                  Padding(
                      padding: const EdgeInsets.all(15.0),
                      child: SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Container(
                                  height: 310,
                                  width: 200,
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(20.0),
                                    child: (Image.asset(
                                      'images/Mem6.jpg',
                                      fit: BoxFit.cover,
                                    )),
                                  ),
                                ),
                                SizedBox(
                                  width: 20,
                                ),
                                Container(
                                  height: 310,
                                  width: 200,
                                  //ClipRRect allows for it to have the border radius. Container is painted behind the image.
                                  //For that reason, adding a border radius to the container doesn't work.
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(20.0),
                                    child: Image.asset(
                                      'images/Mem2.JPG',
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 20,
                                ),
                                Container(
                                  height: 310,
                                  width: 200,
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(20.0),
                                    child: (Image.asset(
                                      'images/memory-4.jpeg',
                                      fit: BoxFit.cover,
                                    )),
                                  ),
                                ),
                              ])))
                ]))));
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM