flutter 修复类型“List< dynamic>”不是类型“Map〈String,dynamic>”的子类型

crcmnpdw  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(220)

我有一个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的列表,以便在应用程序运行时可以看到它。

xtfmy6hx

xtfmy6hx1#

因为我看到API将返回多个元素,所以它是List,对吗?
在此行中:

return Workouts_Model.fromJson(jsonDecode(response.body));

您尝试将List赋值给Map<String, dynamic>,这是错误的,您需要在API中为数据的List生成一个List<Workouts_Model>,因此请将您的方法替换为:

static Future<List<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();
print(responseJson);

if (response.statusCode == 200) {
  return workoutsModelFromJson(response.body);
} else {
  throw Exception('Failed to load User');
}
}

然后更改为:

late Future<Workouts_Model> futureWorkouts;

更改为:

late Future<List<Workouts_Model>> futureWorkouts;

然后在您的FutureBuilder

FutureBuilder<List<Workouts_Model>>(
          future: futureWorkouts,
          builder: (BuildContext context, AsyncSnapshot<List<Workouts_Model>> snapshot) {
            if (snapshot.hasData) {
              return Column(
               children: List.generate(snapshot.data!.length, (index) => Text(snapshot.data![index].name ?? 'noname')));
            } else if (snapshot.hasError) ;
            print(snapshot.error);
            {
              return Text('${snapshot.error}');
            }
            return const CircularProgressIndicator();
          },
        ),

相关问题