[英]Dart Exception has occurred. _CastError (type 'String' is not a subtype of type 'int' in type cast) Error
[英]Unhandled Exception: type 'String' is not a subtype of type 'Future<String>' in type cast
我收到這個錯誤,誰能幫我解決這個錯誤
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() function 中使用了上面的 function
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);
}
表達方式:
(await ApiService.get_video_lecture_subject(schoolId, classNo)) as Future<String>
調用您的方法get_video_lecture_subject
。 這將返回一個Future<String>
。 然后,您等待那個未來,這會產生一個String
。
然后,您嘗試將該String
轉換為Future<String>
。 那失敗了,因為字符串不是未來。
嘗試刪除as Future<String>
。
用這個替換行
final res = await ApiService.get_video_lecture_subject(schoolId, classNo);
更新:更改變量名稱(也許它的類型被初始化為 Future)
查看此示例示例,讓我知道它是否有效
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('')),
));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.