首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何更全面地将Future<List<T>>类型转换为<List<T>>类型?

如何更全面地将Future<List<T>>类型转换为<List<T>>类型?
EN

Stack Overflow用户
提问于 2022-09-11 12:27:11
回答 1查看 49关注 0票数 0

所有人!我在用doofinder开发电子商务应用程序。但我面临着一个棘手的问题。我试图从doofinder(这只是搜索服务) API中获取数据,然后呈现到屏幕上。我加了屏幕截图。

代码语言:javascript
运行
复制
Future<List<Product>> fetchProduct(query) async {
  var response = await http.get(
    Uri.parse(
        'https://eu1-search.doofinder.com/5/search?hashid=30a5f&query=$query'),
    // Send authorization headers to the backend.
    headers: {'Authorization': 'c59dadc5d822ca2b134f170'},
  );
  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    print(jsonDecode(response.body)['results'].toList().runtimeType);
    return jsonDecode(response.body)['results'].toList().cast<List<Product>>();
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

那么,

代码语言:javascript
运行
复制
              onChanged: (_) => EasyDebounce.debounce(
                'tFMemberController',
                const Duration(milliseconds: 800),
                () {
                  isSearchStarted =
                      textController!.text.isNotEmpty &&
                          textController!.text.trim().length > 0;
                  print('isSearchStarted $isSearchStarted');
                  if (isSearchStarted) {
                    print('${textController!.text.trim()}');
                    searchedProducts =
                        fetchProduct(textController!.text)
                            as List<Product>;
                    print(searchedProducts);
                  }
                  setState(() {});
                },
              ),

这是错误日志。

代码语言:javascript
运行
复制
E/flutter ( 5295): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'Future<List<Product>>' is not a subtype of type 'List<Product>' in type cast
E/flutter ( 5295): #0      _SearchPageState.build.<anonymous closure>.<anonymous closure> (package:s4s_mobileapp/search/page_search.dart:151:41)
E/flutter ( 5295): #1      EasyDebounce.debounce.<anonymous closure> (package:easy_debounce/easy_debounce.dart:44:22)
E/flutter ( 5295): #2      Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter ( 5295): #3      _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter ( 5295): #4      _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter ( 5295): #5      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
E/flutter ( 5295): 
I/flutter ( 5295): List<dynamic>
E/flutter ( 5295): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'CastList<dynamic, List<Product>>' is not a subtype of type 'FutureOr<List<Product>>'
E/flutter ( 5295): #0      fetchProduct (package:s4s_mobileapp/search/page_search.dart:41:58)
E/flutter ( 5295): <asynchronous suspension>
E/flutter ( 5295): 

这让我发疯了。我希望你仔细看看下面的图片,并找到一个合适的解决方案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-11 12:44:36

变化

代码语言:javascript
运行
复制
jsonDecode(response.body)['results'].toList().cast<List<Product>>();

对此:

代码语言:javascript
运行
复制
jsonDecode(response.body)['results'].toList().cast<Product>();

cast方法已经知道您正在处理列表,只想知道元素的类型,而不想知道列表本身的类型。

编辑:您还需要更改:

代码语言:javascript
运行
复制
searchedProducts = fetchProduct(textController!.text) as List<Product>;

对此:

代码语言:javascript
运行
复制
searchedProducts = fetchProduct(textController!.text) as Future<List<Product>>;

您必须使用期货,因为您的结果是异步处理。在小部件树中,您必须使用FutureBuilder,它获取未来,并根据需要构建列表。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73679269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档