简体   繁体   中英

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. 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

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();
}
}

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