flutter : Exception has occurred. _TypeError (type 'Future<dynamic>' is not a subtype of type 'Uint8List')

Viewed 107

heloo, I want to create a pdf file with list image. When I run my button code I get error message Exception has occurred. _TypeError (type 'Future' is not a subtype of type 'Uint8List').

My button :

ButtonWidget(
              text: 'Export PDF',
              onClicked: () async {
                final pdfFile = await ExportPdfApi.generateMyPDF();
                ExportPdfApi.openFile(pdfFile);
              },
            ),

Function get image :

static viewImage(image) async {
print("print $image");

final imageJpg1 = (await NetworkAssetBundle(Uri.parse(image)).load(image))
    .buffer
    .asUint8List();

print("print $imageJpg1");

return imageJpg1;
}

Listview in my pdf :

ListView.builder(
          itemCount: _listAnggotaController.dataList.length,
          itemBuilder: (context, index) {
            return ClipRRect(
              horizontalRadius: 32,
              verticalRadius: 32,
              child: Image(
                MemoryImage(viewImage(
                    _listAnggotaController.dataList[index].idGambar)),
                height: 100,
              ),
            );
          }),

Please help my problem. Thank you.

1 Answers

Firstly Flutter returns a Future when the asynchronous functions is not completed, when it is completed it will return data of type type. The mistake you are making is calling a asynchronous from a synchronous function. Although dart will execute the functions asynchronously (You can validate this by printing the imageJpg1 from the asynchronous function). But the place you are calling it from is not waiting for the asynchronous function to finish.

I recommend using FutureBuilder.

I hope it is clear now. For more clarity visit Asynchronous Programming

Related