openfoodfacts / openfoodfacts-dart

Open Food Facts API Wrapper
https://pub.dev/packages/openfoodfacts
Apache License 2.0
169 stars 67 forks source link

image of the product or nutrient levels is always null or empty list #136

Closed kiromousa closed 3 years ago

kiromousa commented 3 years ago

Hi everyone! I’m using open food facts api in my flutter app, it works fine and return the product name, but the image of the product or nutrient levels is always null or empty list. e.g: Shiitake Pastete (Barcode: 4104420173194), I can get all the info about this product by the website or open food facts application , but I get this when I use the api :

(keys are :[code, product_name, brands, lang, selected_images, images, nutriments, additives_tags, allergens_tags, nutrient_levels, ingredients_analysis_tags]....... values are :[null, Shiitake Pastete, null, -, {}, {}, {}, [], [], {}, [en:maybe-vegan, en:maybe-vegetarian, en:maybe-palm-oil-free]])

MohamedFBoussaid commented 3 years ago

Hey @kiromousa can you please share with us the version that you are using? And the code that you are using to get the product details ? Thanks.

M123-dev commented 3 years ago

@kiromousa the image list itself is very confusing, I would recommend you to use the picture urls from the product, you can then display them. I think its product.imageFrontUrl imageNutritionUrl imageIngredientsUrl imagePackagingUrl

kiromousa commented 3 years ago

@MohamedFBoussaid

version is : openfoodfacts: ^0.3.15+3 here is the code:

import 'package:auto_size_text/auto_size_text.dart'; import 'package:carousel_slider/carousel_slider.dart'; import 'package:flutter/material.dart'; import 'package:backendless_sdk/backendless_sdk.dart'; import 'package:flutter_custom_clippers/flutter_custom_clippers.dart'; import 'package:prodwirklichkeit/model/ProductsInfo.dart'; import 'main.reflectable.dart'; // Import generated code import 'dart:async'; import 'package:flutter/services.dart'; import 'package:prodwirklichkeit/add_product_screen.dart'; import 'package:barcode_scan/barcode_scan.dart'; import 'package:openfoodfacts/openfoodfacts.dart';

main() { WidgetsFlutterBinding.ensureInitialized(); initializeReflectable(); // Set up reflection support. runApp(MyApp()); }

class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: "Identify", home: HomePage(), routes: { AddProductScreen.routeName: (ctx) => AddProductScreen(), HomePage.routeName: (ctx) => HomePage(), }); } }

class HomePage extends StatefulWidget { static const String routeName = "/HomePage";

@override _MyHomePageState createState() => _MyHomePageState(); }

class _MyHomePageState extends State { String value1;

String beforeImage; String afterImage;

AppBar appBar = AppBar( // shape: RoundedRectangleBorder( // borderRadius: BorderRadius.vertical(bottom: Radius.circular(10)) // ), elevation: 0.0, centerTitle: true, backgroundColor: Color(0xff2b2b38), title: const Text('Barcode scan'), );

@override void initState() { super.initState();

}

// List listProducts; String productName = ""; var productData; var productIngredients;

Future getData(String barcode) async{ ProductQueryConfiguration configuration = ProductQueryConfiguration(barcode, language: OpenFoodFactsLanguage.ENGLISH, fields: [ProductField.NAME]); var result = await OpenFoodAPIClient.getProduct(configuration).then((value) { if (value.status == 1) { productName = value.product.productName +" "+barcode; productIngredients = value.product.nutrientLevels.levels.length.toString(); productData = value.product.toData().keys.toList(); print(productData); productData = value.product.toData().values.toList(); print(productData); print(productName); print(productIngredients);

    setState(() {

    });
    return productName;

  } else {
    productName="product not found, please insert data for " ;
    setState(() {

    });
  }
});

}

Future _scanBarcode(BuildContext context) async { ScanResult scanResult = await BarcodeScanner.scan().then((value) { value1 = value.rawContent;

  getData(value1);
}

);

}

final _scaffoldKey = GlobalKey();

@override Widget build(BuildContext context) { final mediaQuery = MediaQuery.of(context); return MaterialApp( home: Scaffold( key: _scaffoldKey, backgroundColor: Color(0xff2b2b38), appBar: appBar, body: Builder(builder: (BuildContext context) {

        return Container(
          height: (mediaQuery.size.height -
              appBar.preferredSize.height -
              mediaQuery.padding.top),
          child: Stack(
            alignment: AlignmentDirectional.center,
            children: [
              Positioned(
                bottom: 0,
                child: ClipPath(
                  clipper: OvalTopBorderClipper(),
                  child: Container(
                    height: (mediaQuery.size.height -
                            appBar.preferredSize.height -
                            mediaQuery.padding.top) *
                        0.99,
                    width: mediaQuery.size.width,
                    decoration: BoxDecoration(color: Color(0xffc63756)),
                  ),
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    alignment: Alignment.center,
                    height: (mediaQuery.size.height -
                            appBar.preferredSize.height -
                            mediaQuery.padding.top) *
                        0.99,
                    width: mediaQuery.size.width,
                    decoration: BoxDecoration(

                      borderRadius: BorderRadius.all(Radius.circular(10)),

                    ),
                    child: Flex(
                      direction: Axis.vertical,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          height: (mediaQuery.size.height -
                                  appBar.preferredSize.height -
                                  mediaQuery.padding.top) *
                              0.9,
                          width: mediaQuery.size.width,
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(10),
                            child: Image(
                              fit: BoxFit.cover,
                                image:
                                    AssetImage("assets/images/search.png")
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              Positioned(
                bottom: 10,
                child: RaisedButton(
                    elevation: 10,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(18.0),
                    ),
                    onPressed: () => _scanBarcode(context),
                    child: Text("Scan")),
              ),
              productIngredients == null ? Text("no nutrients") :
              Text(productIngredients,style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),),
              Text(productName,style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),),
              // Image(image: NetworkImage(productImage)),
            ],
          ),
        );

    }),
    floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
    floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        heroTag: 'btn1',
        onPressed: () {
          Navigator.push(
              context,
              new MaterialPageRoute(
                  builder: (context) => new AddProductScreen()));
        }),
  ),
);

} }

MohamedFBoussaid commented 3 years ago

@kiromousa first thing that I have notice on your code is : ProductQueryConfiguration(barcode, language: OpenFoodFactsLanguage.ENGLISH, fields: [ProductField.NAME]); Maybe you should change it to ProductField.IMAGES or ProductField.ALL, otherwise you will get only the name field and the rest will be ignored.

Then for the following values you can change it to: productIngredients = value.product.ingredientsText;

For the product image you can have something like this (for the next release this will be much easier) : var frontImageUrl = value.product.images .singleWhere((image) => image.field == ImageField.FRONT && image.size == ImageSize.DISPLAY).url;

For the nutrition level, do you mean the nutrition score ? On Open Food Facts API there is no images for that, but there is the level as String, so you can read the nutrition level value and then you decide which image you show (But first you need to add the nutrition images to your asset folder): To get the level value you can do:

String nutriScore = value.product.nutriscore

And what are you trying to get here ? productData = value.product.toData().keys.toList();

@kiromousa please check all this and come back to me if this solve your issue.

kiromousa commented 3 years ago

@MohamedFBoussaid thank you very much! everything worked out! i am very grateful to you!

MohamedFBoussaid commented 3 years ago

@kiromousa happy to help !