'How can i refresh data immediately after updating it in flutter?

so here i'm trying to to update quantity in product_inventory table that links between products and inventories,
however it's updated in the database but not in the screen until i use ctrl+S.
i tried to use many possible ways as calling the quantity in different way even in setState but none of them worked, how can i make the data change after the quantity update.
also i'm using an API with laravel

class ProductsInInventoryWidget extends StatefulWidget
{
  ProductsInInventory? model;
  BuildContext? context;
  //final ValueChanged onPressed;

  ProductsInInventoryWidget({this.model,this.context});

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



class _ProductsInInventoryWidgetState extends State<ProductsInInventoryWidget> {

  var apiCall = new APICall();
   addQuantity(String mydata) async
  {
    String Product_BarCode = widget.model!.productBarcode.toString();
    String Inventory_id = widget.model!.inventoryId.toString();
    var response = await http.put(
        Uri.parse("http://192.168.1.188:8000/api/user/IncrementProduct/"+Product_BarCode+"/"+Inventory_id,),
      body:jsonEncode(<String, String>{
        'quantity': mydata,
      }),
    );

     // setState(() {
     //   response;
     //   mydata = widget.model!.quantity.toString();
     // });

  }

  @override
  Widget build(BuildContext context) {
    var quantityData = widget.model!.quantity.toString();
    return InkWell(
        onTap: ()
        {
        //  Navigator.push(context, MaterialPageRoute(builder: (c)=> ProductsInInventoryForm(model: widget.model)));
        },
        splashColor: Colors.amber,
        child:  Padding(
            padding: EdgeInsets.only(top:0.0),
            child : Card(

              margin: EdgeInsets.fromLTRB(5, 6, 5, 0),
              child: Padding(
                padding:  EdgeInsets.fromLTRB(10, 10, 10, 10),
                child: Column(
                  children: [
                    ListTile(
                      leading: CircleAvatar(
                        radius:40,
                        backgroundColor: Colors.black38,
                        child: Text(quantityData
                          ,style: TextStyle(
                          color: Colors.white
                        ),),
                      ),
                      title: Text(widget.model!.productName), //(widget.model!.ProductName!,),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [

                          Text("code bar : " + widget.model!.productBarcode ),
                          Text("updated : " +  DateFormat('yyyy-MM-dd kk:mm').format(widget.model!.updatedAt)),
                          Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              IconButton(
                                icon: Icon(Icons.add,color: Colors.blue,),

                                onPressed: ()async {
                                  onRefresh: () { setState((){
                                    // Update your data here
                                    addQuantity(quantityData);
                                  }); };
                                  setState(() {
                                  //  widget.onPressed;
                                    addQuantity(quantityData);
                                    quantityData = widget.model!.quantity.toString();
                                  });
                                }
                              ),
                              IconButton(
                                icon: Icon(Icons.remove,color: Colors.blue,),
                                onPressed: () {
                                  // Perform some action
                                },

                              ),
                              FlatButton(
                                onPressed: () {
                                  // Perform some action
                                },
                                child: const Text('Delete',style: TextStyle(color: Colors.blue),),
                              ),

                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            )
        )
    );
  }
}


Solution 1:[1]

i found the solution i just had to change it in the ui seperatly by changing "quantityData" to an int and increment it in the setstate, this way it keeps updating in the screen

class ProductsInInventoryWidget extends StatefulWidget
{
  ProductsInInventory? model;

  BuildContext? context;



  ProductsInInventoryWidget({this.model,this.context});

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



class _ProductsInInventoryWidgetState extends State<ProductsInInventoryWidget> {



  int quantityData =1;




  Future addQuantity(int mydata) async
  {
    String Product_BarCode = widget.model!.productBarcode.toString();
    String Inventory_id = widget.model!.inventoryId.toString();
    var response = await http.put(
      Uri.parse("http://192.168.1.188:8000/api/user/IncrementProduct/$Product_BarCode/$Inventory_id/$mydata",),
      body:jsonEncode(<String, String>{
        'quantity': mydata.toString(),
      }),
    );
    var body = jsonDecode(response.body);



  }


  Future<http.Response> DeleteProductFromInventoryProducts(int join_id) async
  {
    final http.Response response = await http.delete(
      Uri.parse("http://192.168.1.188:8000/api/user/deleteProductsFromInventory/$join_id",)
    );

    return response;


  }

  @override
  void initState() {
    // TODO: implement initState
    quantityData = widget.model!.quantity; // 2# assign the incoming data here
    super.initState();

  }


  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: EdgeInsets.only(top:0.0),
        child : Card(

          margin: EdgeInsets.fromLTRB(5, 6, 5, 0),
          child: Padding(
            padding:  EdgeInsets.fromLTRB(10, 10, 10, 10),
            child: Column(
              children: [
                ListTile(
                  leading: CircleAvatar(
                    radius:40,
                    backgroundColor: Colors.black38,
                    child: Text(quantityData.toString()
                      ,style: TextStyle(
                      color: Colors.white
                    ),),
                  ),
                  title: Text(widget.model!.productName), //(widget.model!.ProductName!,),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [

                      Text("code bar : " + widget.model!.productBarcode ),
                      Text("updated : " +  DateFormat('yyyy-MM-dd kk:mm').format(widget.model!.updatedAt)),
                      Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          IconButton(
                            icon: Icon(Icons.add,color: Colors.blue,),

                            onPressed: () async{

                             // await addQuantity(quantityData);



                              setState(() {

                                quantityData+=1;
                                print(quantityData.toString());
                                addQuantity(quantityData);
                              });


                            }
                          ),
                          IconButton(
                            icon: Icon(Icons.remove,color: Colors.blue,),
                            onPressed: () {
                              // Perform some action
                            },

                          ),
                          FlatButton(
                            child: const Text('Delete',style: TextStyle(color: Colors.blue),),
                            onPressed: () {
                              // Perform some action
                              setState(() {
                             //   DeleteProductFromInventoryProducts(widget.model!.id.toString());
                              });
                            },

                          ),

                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        )
    );
  }
}```

Solution 2:[2]

 Future addQuantity(String mydata) async
  {
    String Product_BarCode = widget.model!.productBarcode.toString();
    String Inventory_id = widget.model!.inventoryId.toString();
    var response = await http.put(
        Uri.parse("http://192.168.1.188:8000/api/user/IncrementProduct/"+Product_BarCode+"/"+Inventory_id,),
      body:jsonEncode(<String, String>{
        'quantity': mydata,
      }),
    );

     // setState(() {
     //   response;
     //   mydata = widget.model!.quantity.toString();
     // });

  }

and call method like that

 await addQuantity(quantityData);

Solution 3:[3]

Here I did some steps on how you can resolve the issue, check the comments steps:

class _ProductsInInventoryWidgetState extends State<ProductsInInventoryWidget> {

  var apiCall = new APICall();
  String? quantityData;   // <--- 1# add this variable here


  Future<void> addQuantity(String mydata) async
  {
    String Product_BarCode = widget.model!.productBarcode.toString();
    String Inventory_id = widget.model!.inventoryId.toString();
    var response = await http.put(
      Uri.parse("http://192.168.1.188:8000/api/user/IncrementProduct/"+Product_BarCode+"/"+Inventory_id,),
      body:jsonEncode(<String, String>{
        'quantity': mydata,
      }),
    );

    setState(() {
      // quantityData = responseResult    6# Finally you should assing the new response data from Laravel to quantityData variable
                                          // I do not know how you are receiving this data so get the response and them add it gere.  
    });

  }

  @override
  void initState() {
    // TODO: implement initState
    quantityData = widget.model!.quantity.toString(); // 2# assign the incoming data here
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
        onTap: ()
        {
          //  Navigator.push(context, MaterialPageRoute(builder: (c)=> ProductsInInventoryForm(model: widget.model)));
        },
        splashColor: Colors.amber,
        child:  Padding(
            padding: EdgeInsets.only(top:0.0),
            child : Card(

              margin: EdgeInsets.fromLTRB(5, 6, 5, 0),
              child: Padding(
                padding:  EdgeInsets.fromLTRB(10, 10, 10, 10),
                child: Column(
                  children: [
                    ListTile(
                      leading: CircleAvatar(
                        radius:40,
                        backgroundColor: Colors.black38,
                        child: Text(quantityData!  // 3# update to null safe
                          ,style: TextStyle(
                              color: Colors.white
                          ),),
                      ),
                      title: Text(widget.model!.productName), //(widget.model!.ProductName!,),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [

                          Text("code bar : " + widget.model!.productBarcode ),
                          Text("updated : " +  DateFormat('yyyy-MM-dd kk:mm').format(widget.model!.updatedAt)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              IconButton(
                                  icon: Icon(Icons.add,color: Colors.blue,),

                                  onPressed: () async {
                                      await addQuantity(quantityData!);  // 4# remove set state from here and add await to it to stop until it finishes
                                                                         // why remove setState? because you are using it in the function call
                                  }
                              ),
                              IconButton(
                                icon: Icon(Icons.remove,color: Colors.blue,),
                                onPressed: () {
                                  // Perform some action
                                },

                              ),
                              FlatButton(
                                onPressed: () {
                                  // Perform some action
                                },
                                child: const Text('Delete',style: TextStyle(color: Colors.blue),),
                              ),

                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            )
        )
    );
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yassine Haddaj
Solution 2 benten
Solution 3