【发布时间】:2021-11-12 05:12:36
【问题描述】:
我正在构建一个颤振网页,其中包含从 api 检索的数据,几乎一切正常,但我遇到了这个问题。该api只接受一个参数'{“url”:“”}',并且我的代码中的所有内容都有效,因为如果我尝试在控制台中打印结果,它就可以工作。我唯一的问题是在屏幕上显示数据时,即使我将他期望的类型传递给他,颤振也给了我这个错误。
这是我的代码:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
Future<Album> fetchAlbum() async {
final headers = {"Content-type": "text/plain"};
final json = '{"url": ""}';
final response = await post(
Uri.parse('myapikey'),
headers: headers,
body: json);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
print(response.body);
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
final String url;
Album({
required this.url,
});
factory Album.fromJson(Map<List<dynamic>, dynamic> json) {
return Album(url: json['']);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Test'),
),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.url);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}
有人可以帮我吗?
【问题讨论】:
-
参考我的回答here希望对你有所帮助
-
您好,感谢您的回答。我之前尝试过这个,但得到了同样的错误,因为我的 api 接受的参数只有一个,而不是像 json 占位符那样的 3 个
-
你能添加你的 API url
-
不,很遗憾,我不能,这不是我的财产,所以出于安全原因,我不能发布网址
标签: flutter api dart flutter-web