如何在 flutter 中更新数据后立即刷新数据?

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

所以我在这里尝试更新 product_inventory table 中产品和库存之间的链接数量,
然而,它在数据库中更新,但在我使用 ctrl+S 之前不会在屏幕中更新。
我尝试使用许多可能的方式,即使在 setState 中也以不同的方式调用数量,但其中 none 有效, 数量更新后如何修改数据
我也在使用 API 和 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),),
                              ),

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

  }

然后像这样调用方法

 await addQuantity(quantityData);

这里我做了一些关于如何解决问题的步骤,查看评论步骤:

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),),
                              ),

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

我找到了解决方案,我只需要在 ui 中单独更改它,方法是将“数量数据”更改为 int 并在设置状态中递增它,这样它就会在屏幕上不断更新

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

                          ),

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