【问题标题】:Using Provider in a Stateful Widget在有状态的小部件中使用 Provider
【发布时间】:2021-01-20 18:38:35
【问题描述】:

我对 Flutter/Firebase 还很陌生,并且对于一个非常简单的 CRUD 联系人应用程序的 Provider 实现存在问题。我不确定如何解决这个问题。

[VERBOSE-2:ui_dart_state.cc(166)] 未处理的异常:'package:provider/src/provider.dart':断言失败:第 284 行 pos 7:'T != dynamic':试图调用 Provider。的。这可能是一个错误,因此 不受支持。 如果您想公开一个可以是任何东西的变量,请考虑更改 dynamic 改为 Object

这是完成保存页面的代码。

actions: [
        IconButton(
            icon: Icon(
              Icons.done,
              color: Colors.white,
            ),
            onPressed: () async {
              //save data to firebase
              final uid = await Provider.of<dynamic>(context, listen: false)
                  .auth
                  .getCurrentUID();

              await db
                  .collection("userData")
                  .doc(uid)
                  .collection('contacts')
                  .add(
                {
                  'Name': widget.contact.name,
                  'PhoneNumber': widget.contact.phoneNumber,
                  'Location': widget.contact.location,
                  'Notes': widget.contact.notes
                },
              );

谢谢

【问题讨论】:

    标签: flutter google-cloud-firestore


    【解决方案1】:

    错误信息是不言自明的。

    您需要在 Provider.of 语句中使用正确的类型(或Object)而不是动态的。

    await Provider.of<CorrectType>(context, listen: false)
      .auth
      .getCurrentUID();
    

    【讨论】:

    • 好的,我试过了——我现在得到'getter 'auth' is not defined for type Object
    • 如果您知道类型,那么最好使用它。对于 Object,您必须使用 as 进行投射。 Object a = 1; var b = 2 + a as int;
    • 我怎么知道它是什么类型的?这是我的模型文件:class Contact extends ChangeNotifier { String name; String location; int phoneNumber; String notes;Contact(this.name, this.phoneNumber, this.location, this.notes); Map&lt;String, dynamic&gt; toJson() =&gt; { 'Name': name, 'PhoneNumber': phoneNumber, 'Location': location, 'Notes': notes }; notifyListeners(); }
    • 此类没有您尝试使用的 auth 字段。
    • 很高兴为您提供帮助
    猜你喜欢
    • 2020-02-19
    • 1970-01-01
    • 2020-10-19
    • 2021-01-26
    • 1970-01-01
    • 2018-08-07
    • 2021-12-15
    • 2021-06-11
    • 2021-12-24
    相关资源
    最近更新 更多