Home > Blockchain >  How to convert the type Future<List<T>> to <List<T>> in fultter?
How to convert the type Future<List<T>> to <List<T>> in fultter?

Time:09-12

everyone! I was developing e-commerce flutter app with doofinder APIs. But I faced a thorny problem. I tried to get data from doofinder(it's just search service) API then present to screen. I added screen-shots. search screen on mobile emulator

enter image description here

enter image description here

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');
  }
}

then,

              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(() {});
                },
              ),

And this is error log.

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): 

This makes me crazy. I want you to take a closer look at the pictures below and find a suitable solution please.

CodePudding user response:

Change

jsonDecode(response.body)['results'].toList().cast<List<Product>>();

to this:

jsonDecode(response.body)['results'].toList().cast<Product>();

The cast method already knows that you are working with lists and only wants to know the type of the elements, but not the type of the list itself.

EDIT: You also need to change:

searchedProducts = fetchProduct(textController!.text) as List<Product>;

to this:

searchedProducts = fetchProduct(textController!.text) as Future<List<Product>>;

You have to work with futures as your result is processed asynchronously. In the widget tree you have to use FutureBuilder which takes a future and builds your list as you want.

  • Related