我正在弄错这个错误,有人可以帮我解决这个错误吗
static Future<String> get_video_lecture_subject(int schoolId,int classroom) async {
var body;
body = jsonEncode({
"school_id": schoolId,
"classroom": classroom,
});
final response = await http.post(
'https://b5c4tdo0hd.execute-api.ap-south-1.amazonaws.com/testing/get-video-lecture-subjects',
headers: {"Content-Type": "application/json"},
body: body,
);
print(response.body.toString());
return response.body.toString();
}
我在getpref()函数中使用了上面的函数
getpref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int classNo = int.parse(prefs.getString("class")[0]);
int schoolId = prefs.getInt("school_id");
print("hello");
response=(await ApiService.get_video_lecture_subject(schoolId, classNo)) as Future<String> ;
print(response);
}
答案 0 :(得分:0)
表达式:
(await ApiService.get_video_lecture_subject(schoolId, classNo)) as Future<String>
调用您的方法get_video_lecture_subject
。返回Future<String>
。
然后,您等待那个未来,结果是String
。
然后,您尝试将String
转换为Future<String>
。失败是因为字符串不是未来。
尝试删除as Future<String>
。
答案 1 :(得分:0)
用该行替换
final res = await ApiService.get_video_lecture_subject(schoolId, classNo);
更新:更改变量名称(也许它的类型已初始化为Future)
答案 2 :(得分:0)
查看此示例示例,让我知道它是否有效
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
getPrefs();
runApp(MyApp());
}
void getPrefs() async {
String value = await yourfunction();
print(value);
}
Future<String> yourfunction() {
final c = new Completer<String>();
// Below is the sample example you can do your api calling here
Timer(Duration(seconds: 1), () {
c.complete("you should see me second");
});
// Process your thigs above and send the string via the complete method.
// in you case it will be c.complete(response.body);
return c.future;
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child:
/* FutureBuilder<String>(
future: yourfunction(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data);
}
return CircularProgressIndicator();
}), */
Text('')),
));
}
}