Home > other >  I am getting this error in my flutter/dart code "Unhandled Exception: type 'Future<dyna
I am getting this error in my flutter/dart code "Unhandled Exception: type 'Future<dyna

Time:07-11

Context : I am trying to send a request using a session ID that I have stored in the cache. This session ID was retrieved from the http response from a previous login screen.

I am able to display the cached Session ID but when I try to send the request using the cached Session ID I am getting this error "Unhandled Exception: type 'Future' is not a subtype of type 'String' in type cast"

Thanks for the help!

Here is the code that I am using :

import 'package:cache_manager/cache_manager.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class messageBoard extends StatefulWidget {
   messageBoard({Key key}) : super(key: key);
   
  @override
  State<messageBoard> createState() => _messageBoardState();
}

class _messageBoardState extends State<messageBoard> {

  final _sessionIDController = ReadCache.getString(key: "cache");

  void messageBoardReq() async {

    var map = <String, dynamic>{
      "SessionID": _sessionIDController,
    };

    var res = await http.post(
      Uri.parse("http://192.168.1.8:8080/HongLeong/MENU_REQUEST.do"),
      body: map,
    );

    final data = jsonDecode(res.body);
    print(data);

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: [
          Center(
            child: CacheManagerUtils.cacheTextBuilder(
            textStyle: TextStyle(color: Colors.black), cacheKey: "cache"),
          ),
          RawMaterialButton(
            onPressed: () {
              messageBoardReq();
            },
            elevation: 2.0,
            fillColor: Colors.white,
            padding: const EdgeInsets.all(15.0),
            shape: const CircleBorder(),
            child: const Icon(
              Icons.forum,
              size: 35.0,
            ),
          ),
        ],
      )
    );
  }
}

CodePudding user response:

There is a missing await to get the value out of the Future.

It should be like this:

    var map = <String, dynamic>{
      "SessionID": await _sessionIDController, // <- Here
    };

CodePudding user response:

if _sessionIDController returns a Future you should add an await and wait for the execution and assigning of proper format

var map = <String, dynamic>{
  "SessionID": await _sessionIDController
};

//now if _sessionIDController has a return type of Future then SessionID will be assigned with a datatype of String.

  • Related