【问题标题】:onFieldSubmitted of TextFormFeild repetitive call upon calling future function - Flutter在调用未来函数时重复调用 TextFormFeild 的 onFieldSubmitted - Flutter
【发布时间】:2021-03-30 02:09:29
【问题描述】:

场景:

我有一个TextFormFeild,用户在其中输入产品名称进行搜索。如果搜索到的产品在数据库中不可用,那么我想将该搜索到的产品存储在数据库中。为此,我有函数storeUserSearchedValue(),它在其中调用未来函数。 在谷歌搜索这个问题后,我发现在颤振的构建阶段调用未来会导致重复调用。

如何在onFieldSubmitted函数的数据库中存储搜索到的产品的值,而不需要面对函数的不断重复调用?

代码

类显示textfeild 和它的onFieldSubmitted 函数。

class SearchProductView extends StatefulWidget {
  @override
  _SearchProductViewState createState() => _SearchProductViewState();
}

class _SearchProductViewState extends State<SearchProductView> {
 
storeUserSearchedValue(String _userSearchedProduct,List<Product> _productsData) {
    print("I N S I D E    storeUserSearchedValue: " + _userSearchedProduct.toString());
    int _noOfResultsOfUserProducts = 0;
    for (int i = 0; i < _productsData.length; i++) {
      if (_productsData[i].name.contains(_userSearchedProduct)) 
        _noOfResultsOfUserProducts++;
    }
    if (_noOfResultsOfUserProducts == 0)
      SearchviewModel().addCustomerSearchedProducts(_userSearchedProduct);
 }



@override
Widget build(BuildContext context) {
final _allProductsData = Provider.of<List<Product>>(context);

return Scaffold(
............
TextFormField(
     controller: _searchedProductText,
     onFieldSubmitted:
            storeUserSearchedValue(
                 _searchedProductText.text,
                 _allProductsData,
                ),
     onChanged: searchOperation,
    ),
)
.........
}

在数据库中存储数据的实际逻辑

class SearchviewModel extends BaseViewModel {


// -------- Below Function are adding searched product in `customer` collection

addCustomerSearchedProducts(String searchedProductText) async {
    String _currentUser = FirebaseAuth.instance.currentUser;
    Map<String, dynamic> custdataMap = {
      "custSearchedProducts": [searchedProductText, DateTime.now()]
    };
    await updateCustData(custdataMap, _currentUser.uid);
}


 Future<bool> updateCustData(Map<String, dynamic> dataMap, String custID) async {
    // - Dynamically adding data in the db
    dataMap.forEach(
      (key, value) async {
        await FirebaseFirestore.instance.collection('customer').doc(custID).set(
          {
            key: value,
          },SetOptions(merge: true),
        );
      },
    );
    return true;
  }

}

问题的视频表示

【问题讨论】:

  • 您是否尝试添加标志并在再次调用该函数之前进行检查?
  • @ShubhamGupta 什么样的支票?我该如何检查?

标签: flutter dart asynchronous async-await future


【解决方案1】:

在调用storeUserSearchedValue 函数时,只需将textformfeild onFieldSubmitted 属性添加到(_)=&gt;(不是()=&gt;)即可停止重复调用。

onFieldSubmitted: (_)=> storeUserSearchedValue(_searchedProductText.text,_allProductsData),

上面的代码 sn-p 运行良好!

我不太清楚这背后的原因是什么

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2012-02-06
    • 1970-01-01
    • 2016-11-13
    相关资源
    最近更新 更多