[英]Unhandled Exception: type 'Future<dynamic>' is not a subtype of type 'ProductModel' in dart/flutter
[英]I am getting this error in my flutter/dart code "Unhandled Exception: type 'Future<dynamic>' is not a subtype of type 'String' in type cast"
上下文:我正在尝试使用存储在缓存中的会话 ID 发送请求。 此会话 ID 是从上一个登录屏幕的 http 响应中检索到的。
我能够显示缓存的会话 ID,但是当我尝试使用缓存的会话 ID 发送请求时,我收到此错误“未处理的异常:类型‘未来’不是类型转换中‘字符串’类型的子类型”
谢谢您的帮助!
这是我正在使用的代码:
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,
),
),
],
)
);
}
}
缺少await
从Future
中获取值。
它应该是这样的:
var map = <String, dynamic>{
"SessionID": await _sessionIDController, // <- Here
};
如果 _sessionIDController 返回一个 Future 你应该添加一个 await 并等待执行和分配正确的格式
var map = <String, dynamic>{
"SessionID": await _sessionIDController
};
//现在如果 _sessionIDController 的返回类型为 Future,那么 SessionID 将被分配一个 String 的数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.