错误:期望的值类型为'(() => void)?',但实际传入的是'+Future<dynamic>'类型。

3

我正在使用Flutter将数据保存到Firestore中,棘手的部分在于我的TextFormField将数据设置为null或"",因为它在表单页面加载时设置了数据,然后我收到了错误消息:Expected a value of type '(() => void)?', but got one of type '+Future'。

以下是我的代码:

  final barcode = TextEditingController();
  final price = TextEditingController();//these are from my textformfield
  final stock = TextEditingController();
  final color = TextEditingController();

  addData() async {
    // ASYNC HERE
    Map<String, dynamic> theData = {
      "Color": color.text,
      "Price": price.text,
      "Stock": stock.text,
    };
    CollectionReference collectionReference = Firestore.instance.collection("products");
    await collectionReference.doc(barcode.text).set(theData);
  }

我认为答案可能与某个未来函数有关。

下面是我调用addData的地方:

  FloatingActionButton.extended(
    onPressed: addData(),
    label: Text('Done'),
    icon: Icon(Icons.add),
    backgroundColor: Colors.blue,
  ),

1
你分享的代码似乎没有任何问题。问题可能出现在你调用 addData() 的地方。 - Lee3
已更新问题,希望这有所帮助。 - Mario Niemand
@Randal Schwartz 是正确的。移除括号。 - Lee3
1个回答

6
您需要使用onPressed: addData(不包含括号),这样您就可以推迟代码的调用,直到单击FAB时才执行。 相反,由于在设置FAB时立即调用了它,因此您立即调用了它。糟糕。

非常感谢,这个问题困扰了我几天,结果只是该死的括号。 - Mario Niemand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接