如何修复Flutter中的此错误:应为“Map〈String,dynamic>”类型的值,但得到的是“List”类型的值< dynamic>

ogsagwnx  于 2022-12-19  发布在  Flutter
关注(0)|答案(1)|浏览(156)

我尝试通过API接收一个类别列表,但是我得到了这个错误!当我将froomJson更改为froomJson(List)时,我的变量不接受字符串值,因为它需要一个int值。
我的类别模型
'

import 'dart:convert';

class Category {
  String? id;
  String? tenantId;
  String? userId;
  String? name;
  String? description;
  String? createdAt;
  String? updatedAt;

  Category(
      {this.id,
      this.tenantId,
      this.userId,
      this.name,
      this.description,
      this.createdAt,
      this.updatedAt});

  Category.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    tenantId = json['tenant_id'];
    userId = json['user_id'];
    name = json['name'];
    description = json['description'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = id;
    data['tenant_id'] = tenantId;
    data['user_id'] = userId;
    data['name'] = name;
    data['description'] = description;
    data['created_at'] = createdAt;
    data['updated_at'] = updatedAt;
    return data;
  }
}

'
我的API调用
'

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:mcea_master_application/config/config.dart';
import 'package:mcea_master_application/models/CategoryModel.dart';

final String urlCategories = '${Config.baseUrl}categories';

Future getMceaCategories() async {
  final response = await http.get(Uri.parse(urlCategories), headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'Bearer 6|b8Wi0V95n3fgZyCg3DiJFymdx10jZsX2K58vpVcq',
  });
  if (response.statusCode == 200) {
    var categories = Category.fromJson(jsonDecode(response.body));
    // return jsonDecode(response.body);
    return categories;
  } else {
    throw Exception('Falha ao carregar as categorias!');
  }
}

'
如果直接返回response.body而不Map我模型,它就可以工作!
我的页面
'

import 'dart:html';
import 'dart:js';

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:mcea_master_application/config/config.dart';
import 'package:mcea_master_application/config/mcea-api.dart';
import 'package:mcea_master_application/models/CategoryModel.dart';

// ignore: use_key_in_widget_constructors

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: Text(Config.title),
      ),
      body: FutureBuilder(
          future: getMceaCategories(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              print(snapshot.data);
              return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(snapshot.data[index]['name']),
                    );
                  });
            }
            if (snapshot.hasError) {
              print(snapshot.error);
            }
            return const Center(
              child: CircularProgressIndicator(),
            );
          }),
    );
  }
}

'
我的儿子

[
{
    "id": "6f8c3398-c671-424f-a31c-86c0589ab6a7",
    "tenant_id": "866a0842-e227-41b8-a73a-d224f6599412",
    "user_id": "e66beb23-50ee-46e3-b6c6-d146f7f3987f",
    "name": "Treinos para Perna",
    "description": "Aqui você tem todos os treinos para a perna",
    "created_at": "2022-12-14T22:11:06.000000Z",
    "updated_at": "2022-12-14T22:11:06.000000Z"
},
{
    "id": "a65553cd-4f17-4629-9ef9-648797e4d687",
    "tenant_id": "866a0842-e227-41b8-a73a-d224f6599412",
    "user_id": "e66beb23-50ee-46e3-b6c6-d146f7f3987f",
    "name": "Treinos para a Bunda",
    "description": "Aqui você encontra todos os treinos para a bunda",
    "created_at": "2022-12-14T22:11:21.000000Z",
    "updated_at": "2022-12-14T22:11:21.000000Z"
},
{
    "id": "c8f07e7c-7f25-4713-b4d2-f901a5bda8be",
    "tenant_id": "866a0842-e227-41b8-a73a-d224f6599412",
    "user_id": "e66beb23-50ee-46e3-b6c6-d146f7f3987f",
    "name": "Comece Aqui",
    "description": "Aqui você aprende a usar o nosso aplicativo",
    "created_at": "2022-12-12T23:21:22.000000Z",
    "updated_at": "2022-12-14T22:11:34.000000Z"
}

]
我试过this solutions,但没有什么对我有效!
我的SDK版本

sdk: '>=2.18.5 <3.0.0'
csga3l58

csga3l581#

看起来API在你的代码中返回了一个List,你已经做了这个var categories = Category.fromJson(jsonDecode(response.body)); the响应。body '将是一个类别数组,你可能必须做这样的事情

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:mcea_master_application/config/config.dart';
import 'package:mcea_master_application/models/CategoryModel.dart';

final String urlCategories = '${Config.baseUrl}categories';

Future getMceaCategories() async {
  final response = await http.get(Uri.parse(urlCategories), headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'Bearer 6|b8Wi0V95n3fgZyCg3DiJFymdx10jZsX2K58vpVcq',
  });
  if (response.statusCode == 200) {
    final result = jsonDecode(response.body) as List<Map<String,dynamic>>;
    final categories = result.map((data) => Category.fromJson(data)).toList();

    return categories;
  } else {
    throw Exception('Falha ao carregar as categorias!');
  }
}

相关问题