简体   繁体   English

无法加载资产(图像)颤振

[英]Unable to load asset(Image) Flutter

This is my API code and I'm passing the image path from here into flutter to determine which image to load.这是我的 API 代码,我正在将图像路径从这里传递到颤振中以确定要加载的图像。 However, all of the other data such as price or title are loading but the image is not loading and throwing an error of unable to load asset.但是,所有其他数据(例如价格或标题)正在加载,但图像未加载并抛出无法加载资产的错误。

app.post('/products',(req,res)=>{
    //console.log(req.body.LanguageID);
    //console.log(req.body.CategoryID);
    console.log(req.body);
    res.status(200).json({
        "StatusCode": 200,
        "StatusMessage": "success",
        "Data": [
            {
                "Id": "p8",
                "title": "Sufiyan",
                "ImageAsset": "assets/images/plant3.png",
                "price": 80.0                
            },
            {
                "Id": "p8",
                "title": "Sufiyan",
                "ImageAsset": "assets/images/plant1.png",
                "price": 90.0
            }
        ],
        "Message": null,
        // "localId": '8',
        // "idToken": '',
        // "error": {
        //     "message": ""
        // },
        // "expiresIn": "9"
    });
});
app.listen(5000);

That's how I am loading data from the provider into the widget and unable to comprehend why this is not working as I am a newbie to flutter and unable to understand it.这就是我将数据从提供程序加载到小部件中的方式,并且无法理解为什么这不起作用,因为我是新手,无法理解它。

@override
void initState() {
    // TODO: implement initState
    super.initState();
    //gettingData();

    final productData = Provider.of<Products>(context, listen: false);
    productData.fetchData(context);
    // Create TabController for getting the index of current tab
    _controller = TabController(length: list.length, vsync: this);
    _containerheight = _totalarrayheight(8) * 140;
}

@override
Widget build(BuildContext context) {
    final productData = Provider.of<Products>(context);
    final products = productData.items;
    final featuredProducts = productData.featuredItems;

    _controller!.addListener(() {
      setState(() {
        _selectedIndex = _controller!.index;
        if (_controller!.index == 0) {
          _containerheight =
              140 * _totalarrayheight(products.length.toDouble());
        } else {
          _containerheight =
              140 * _totalarrayheight(featuredProducts.length.toDouble());
        }
      });
      if (kDebugMode) {
        print("Selected Index: " + _controller!.index.toString());
      }
    });

That is my provider code:那是我的提供者代码:

class Products with ChangeNotifier {
    late List<ProductList> _items = [];
    fetchData(context) async {
    _items = await getData();
    notifyListeners();
}

Widget to create the grid for product为产品创建网格的小部件

class NewProductGrid extends StatelessWidget {
    const NewProductGrid({
    Key? key,
    required this.products,
    }) : super(key: key);

    final List<ProductList> products;

    @override
    Widget build(BuildContext context) {
    return StaggeredGridView.countBuilder(
      padding: EdgeInsets.only(right: 30, left: 10, top: 10),
      physics:
          NeverScrollableScrollPhysics(), // to disable GridView's scrolling
      shrinkWrap: false,
      crossAxisCount: 4,
      itemCount: products.length,
      itemBuilder: (BuildContext context, int index) => GestureDetector(
        onTap: () {
          Navigator.of(context).pushNamed(ProductDetail.routeName,
              arguments: {'id': products[index].id});
        },
        child: Container(
          //padding: EdgeInsets.only(left:40.0),
          child: Column(
            children: <Widget>[
              Stack(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(left: 35.0),
                    child: Container(
                      height: 150,
                      width: 150,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(20),
                        color: primary_background_six,
                      ),
                    ),
                  ),
                  Container(
                      child: Image.asset(
                    "${products[index].imageAsset}",
                    fit: BoxFit.cover,
                  )),
                  Container(),
                ],
              ),
              Padding(
                padding: const EdgeInsets.only(left: 20.0),
                child: Text(
                  "\$${products[index].price.toInt()}",
                  style: TextStyle(fontFamily: 'Morganite Light', fontSize: 50),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 20.0),
                child: Text(
                  "${products[index].title}",
                  style: TextStyle(fontFamily: 'PlayFairDisplay', fontSize: 18),
                ),
              ),
            ],
          ),
        ),
      ),
      staggeredTileBuilder: (int index) =>
          StaggeredTile.count(2, index.isEven ? 3 : 3),
      mainAxisSpacing: 4.0,
      crossAxisSpacing: 4.0,
     );
     }
}

screen code where the widget is called.调用小部件的屏幕代码。

Container(
    height: _containerheight,
    child: TabBarView(
    controller: _controller,
    children: <Widget>[
    Container(
    //height: 140.0 * _totalarrayheight(tagObjs.length.toDouble()),
          child: NewProductGrid(
          products: products),
         )

Product list model code:产品列表型号代码:

import 'package:flutter/material.dart';

class ProductList with ChangeNotifier {
    final String id;
    final String title;
    final String imageAsset;
    final num price;
    bool isFavorite;

    ProductList({
     required this.id,
     required this.title,
     required this.price,
     required this.imageAsset,
     this.isFavorite = false,
     });
    factory ProductList.fromMap(Map<String, dynamic> json) {
    return ProductList(
        id: json['id'],
        title: json['title'],
        imageAsset: json['imageAsset'],
        price: json['price']);
     }
    factory ProductList.fromJson(Map<String, dynamic> json) {
    print('Json:');
    print(json);
    return ProductList(
        id: json['id'] ?? '',
        title: json['title'] ?? '',
        imageAsset: json['imageAsset'] ?? '',
        price: json['price'] ?? 0);
    }

    void toggleFavoriteStatus() {
    isFavorite = !isFavorite;
    notifyListeners();
    }
}

The image asset in response has an upper case i and the model of product list has image asset with lower case i响应的图像资产具有大写字母 i,产品列表模型具有小写字母 i 的图像资产

Change the model to this把模型改成这个

import 'package:flutter/material.dart';

 class ProductList with ChangeNotifier {
final String id;
final String title;
final String imageAsset;
final num price;
bool isFavorite;

ProductList({
 required this.id,
 required this.title,
 required this.price,
 required this.imageAsset,
 this.isFavorite = false,
 });
factory ProductList.fromMap(Map<String, dynamic> json) {
return ProductList(
    id: json['id'],
    title: json['title'],
    imageAsset: json['ImageAsset'],
    price: json['price']);
 }
factory ProductList.fromJson(Map<String, dynamic> json) {
print('Json:');
print(json);
return ProductList(
    id: json['id'] ?? '',
    title: json['title'] ?? '',
    imageAsset: json['ImageAsset'] ?? '',
    price: json['price'] ?? 0);
}

void toggleFavoriteStatus() {
isFavorite = !isFavorite;
notifyListeners();
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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