我有一个flutter项目,它从Json中的api返回一个数据列表,我想将数据显示为一个特定键的列表,该键是name,但目前我一直收到:
type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
这里是未来的建设者
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
late Future<Workouts_Model> futureWorkouts;
@override
void initState() {
super.initState();
futureWorkouts = APIService.fetchUserWorkout();
}
...................................
FutureBuilder<Workouts_Model>(
future: futureWorkouts,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.name ?? 'noname');
} else if (snapshot.hasError) ;
print(snapshot.error);
{
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
下面是api_caller:
static Future<Workouts_Model> fetchUserWorkout() async {
var url = Uri.parse(Config.apiURL + Config.userWorkoutsAPI);
final response = await http.get(
url,
headers: {
HttpHeaders.authorizationHeader:
'Token XXXXXXXXXXXXXXX',
},
);
final responseJson = jsonDecode(response.body);
print(responseJson);
if (response.statusCode == 200) {
return Workouts_Model.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load User');
}
}
以下是模型:
import 'dart:convert';
List<Workouts_Model> workoutsModelFromJson(String str) =>
List<Workouts_Model>.from(
json.decode(str).map((x) => Workouts_Model.fromJson(x)));
String workoutsModelToJson(List<Workouts_Model> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Workouts_Model {
Workouts_Model({
required this.id,
required this.user,
required this.name,
});
int id;
String user;
String name;
factory Workouts_Model.fromJson(Map<String, dynamic> json) => Workouts_Model(
id: json["id"],
user: json["user"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"user": user,
"name": name,
};
}
如何在模型中显示name
的列表,以便在应用程序运行时可以看到它。
1条答案
按热度按时间xtfmy6hx1#
因为我看到API将返回多个元素,所以它是
List
,对吗?在此行中:
您尝试将
List
赋值给Map<String, dynamic>
,这是错误的,您需要在API中为数据的List
生成一个List<Workouts_Model>
,因此请将您的方法替换为:然后更改为:
更改为:
然后在您的
FutureBuilder
: