代码之家  ›  专栏  ›  技术社区  ›  JoshuaaMarkkNairr

我在flatter/dart代码“未处理的异常:类型‘Future<dynamic>’不是类型转换中类型‘String’的子类型”中得到了这个错误

  •  0
  • JoshuaaMarkkNairr  · 技术社区  · 2 年前

    上下文:我试图使用存储在缓存中的会话ID发送请求。

    我能够显示缓存的会话ID,但当我尝试使用缓存的会话ID发送请求时,我收到了以下错误:“未处理的异常:类型‘Future’不是类型转换中类型‘String’的子类型”

    谢谢你的帮助!

    以下是我正在使用的代码:

    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,
                ),
              ),
            ],
          )
        );
      }
    }
    
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   lepsch    2 年前

    缺少一个 await 从中获取价值 Future .

    应该是这样的:

        var map = <String, dynamic>{
          "SessionID": await _sessionIDController, // <- Here
        };
    
        2
  •  0
  •   Joel Mathew    2 年前

    如果sessionIDController返回Future,则应添加wait和wait,以执行和分配适当的格式

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