0

Im trying to pass the String variable Name which is set in the 4th from bottom line of code (in my Future getProduct() Class), and display it as text in the body of my testPage Stateful class. It seems like such a simple thing to do however I have no clue to pass it. If anyone is able to help and kindly explain it would be much appreciated.

my dart file:

class testPage extends StatefulWidget {
  String barcodeResult;
testPage({required this.barcodeResult});

  @override
  _testPageState createState() => _testPageState(barcodeResult);
  
}

class _testPageState extends State<testPage> {
  String barcodeResult;
  _testPageState(this.barcodeResult);
@override
Widget build(BuildContext context) {
  getProduct();
  return Scaffold(
    appBar: AppBar(
        backgroundColor: Colors.teal,
        title:Text('Found Your Item',
        style: TextStyle(
        fontFamily: 'Fredoka',
        fontSize: 25,
        ),
        ),
      ),
    body:Center(
      child:
        Text(Name,
          style: TextStyle(fontSize: 30),
        ),
    ),
  );
}

Future<Product?> getProduct() async {
    ProductQueryConfiguration configuration = ProductQueryConfiguration(
      barcodeResult,
      fields: [ProductField.NAME]);

  ProductResult result = await OpenFoodAPIClient.getProduct(configuration);

  if(result.status != 1) {
    print("Error retreiving the product : ${result.status}");;
    }

  String? Name = result.product!.productName;
   debugPrint("Test :${Name}");
}
}
Maisie Brooke
  • 123
  • 1
  • 10
  • You can use a Future Builder: https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html – Kantine Mar 16 '22 at 20:04
  • Does this answer your question? [What is a Future and how do I use it?](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it) – nvoigt Mar 16 '22 at 20:32
  • @Kantine Thank you both for your advice, Ive just tried using a future builder and still very much confused. Is there a way I could make the Name a global variable and access it through different classes that way? – Maisie Brooke Mar 16 '22 at 21:07

1 Answers1

1

You can use like this

ProductQueryConfiguration(widget.barcodeResult,fields:[ProductField.NAME]);

Future<Product?> getProduct() async {
    ProductQueryConfiguration configuration = ProductQueryConfiguration(
      widget.barcodeResult,
      fields: [ProductField.NAME]);

  ProductResult result = await OpenFoodAPIClient.getProduct(configuration);

  if(result.status != 1) {
    print("Error retreiving the product : ${result.status}");;
    }

  String? Name = result.product!.productName;
   debugPrint("Test :${Name}");
}

Happy to help you.

Vasoya Jemish
  • 191
  • 1
  • 10