图像本身加载,但不作为随机列表加载。 -颤振

问题描述 投票:0回答:1

并先谢谢您的协助。

因此,当我在代码的其他区域的容器中使用图像时,可以正确加载图像,但是我也希望其中一些图像在AppBar中随机显示。

鉴于它们确实在代码内的其他位置加载,因此我不怀疑Pubyaml错误。

我对扑扑还是相当陌生,并且列出了一般情况。因此,如果我弄混了列表本身或其调用方式,我不会感到惊讶。

它给我这个错误:

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)
════════════════════════════════════════════════════════════════════════════════════════════════════

这里是代码:

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


我将代码粘贴到第一张图片的最下方,以显示如何在其他位置进行设置。

我不确定问题是否出在appBar内是随机图像,还是我缺少一些代码。希望有人能对此有所启发!

非常感谢。

image list flutter loading assets
1个回答
0
投票

您可以在下面复制粘贴运行完整代码您的img()有错误,您返回了Image.asset并再次包装在Image.asset中,导致重复

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

代码段仅返回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;
  }

工作演示

enter image description here

完整代码

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,
                                    )),
                                  ),
                                ),
                              ])))
                ]))));
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.