【问题标题】:Flutter: type 'Future<dynamic>' is not a subtype of type 'Future<Document>'Flutter:类型 'Future<dynamic>' 不是类型 'Future<Document>' 的子类型
【发布时间】:2021-02-10 04:56:19
【问题描述】:

我收到错误消息“'Future dynamic' 类型不是'Future Document' 类型的子类型”,并且无法弄清楚这个'Future dynamic' 来自哪里。

这里我尝试在 Flutter 中构建一个文档编辑页面,通过 id 从 API 加载文档,并在文档加载时使用 FutureBuilder 实际显示页面:

...

class _UpdateNotePageState extends State<UpdateNotePage> {
  final String id;
  DocumentBloc _bloc;
  Future<Document> document;

  _UpdateNotePageState({this.id}) {
    _bloc = DocumentBloc();
    document = _bloc.getDocument(id);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
          future: document,
          builder: (BuildContext context, AsyncSnapshot<Document> snapshot) {
            if (snapshot.hasData) {
              return Container(
                child: Center(
                  child: Column(
                    children: <Widget>[
                      Text(id),
                      NoteForm(document: snapshot.data),
                    ],
                  ),
                ),
              );
            }
            return new CircularProgressIndicator();
          }),
    );
  }
}

这里是 getDocument() 代码(返回 Future Document):

...
class DocumentRepository {
...
  Future<Document> getDocument(String id) async {
    final response = await _api.get("documents/$id");
    return Document.fromJson(response);
  }
...
}

class DocumentBloc {
...
  getDocument(String id) async {
    return await _documentRepository.getDocument(id);
  }
...
}

这里是 Document.fromJson() 以防万一:

class Document {
...
  Document.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    title = json['title'];
  }
...
}

_api.get() 返回json.decode(response.body.toString())

为什么选择“未来动态”?我做错了什么?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    我已经弄清楚了,这只是不同抽象级别上的同步/异步调用混乱,对 Future 的理解不足等。长话短说,我需要改变它

    getDocument(String id) async {
      return await _documentRepository.getDocument(id);
    }
    

    到这里

    Future<Document> getDocument(String id) async {
      return _documentRepository.getDocument(id);
    }
    

    然后按原样将此_bloc.getDocument(id) 传递给FutureBuilder

    【讨论】:

      【解决方案2】:

      在您的类 DocumentRepository 中,在 getDocument 函数中,进行以下更改 (json.decode(response.body)):-

      class DocumentRepository {
      ...
        Future<Document> getDocument(String id) async {
          final response = await _api.get("documents/$id");
          return Document.fromJson(json.decode(response.body));
        }
      ...
      }
      

      【讨论】:

      • 不相关。响应已经解码。我现在修改问题
      猜你喜欢
      • 2020-09-24
      • 2020-09-11
      • 2020-10-13
      • 2019-08-18
      • 2020-12-09
      • 2019-12-05
      • 1970-01-01
      • 2023-03-30
      • 2021-09-18
      相关资源
      最近更新 更多