错误:应为“Map<String, dynamic>”类型的值,但得到“List<dynamic>”类型的值

时间:2021-04-25 15:08:31

标签: flutter

我试图从我的数据库中获取一些信息,但出现此错误:错误:预期类型为“Map”的值,但得到类型为“List”的值 在我的函数#getData() 我可以找到错误

主页中有我的#getData()函数代码:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:mostapha_app/api/api.dart';
import 'package:mostapha_app/models/userModel/postModel.dart';
import 'package:mostapha_app/models/userModel/userModel.dart';
import 'package:mostapha_app/screens/Home/addpage.dart';

class Home extends StatefulWidget {
  final VoidCallback login;
  Home({this.login});
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Color wc = Colors.white;
  TextStyle st = TextStyle(color: Colors.white);
  List<PostModel> postmodel = [];
  getDta() async {
    var data = await Api.getPost();
    //print(data);
    if (data != null) {
      postmodel.clear();
      for (Map<String, dynamic> i in data) {
        setState(() {
          postmodel.add(PostModel.fromJson(i));
        });
      }
      print(postmodel);
    }
  }

  @override
  void initState() {
    super.initState();
    getDta();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Page d'accuei l"),
          centerTitle: true,
          actions: [
            IconButton(
                icon: Icon(
                  FontAwesomeIcons.signOutAlt,
                  color: Colors.white,
                ),
                onPressed: () {
                  widget.login.call();
                  UserModel.logOut();
                }),
            IconButton(
                icon: Icon(
                  Icons.refresh,
                  color: Colors.white,
                ),
                onPressed: () {
                  print("test");
                  getDta();
                })
          ],
        ),
        body: SingleChildScrollView(
            child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                FlatButton.icon(
                  onPressed: () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (context) => AppPost()));
                  },
                  icon: Icon(
                    Icons.add,
                    color: wc,
                  ),
                  label: Text(
                    "ajouter",
                    style: st,
                  ),
                  color: Colors.green,
                ),
                FlatButton.icon(
                  onPressed: () {},
                  icon: Icon(
                    Icons.add,
                    color: wc,
                  ),
                  label: Text(
                    "Modifier",
                    style: st,
                  ),
                  color: Colors.yellow,
                ),
                FlatButton.icon(
                  onPressed: () {},
                  icon: Icon(
                    Icons.add,
                    color: wc,
                  ),
                  label: Text(
                    "Supprimer",
                    style: st,
                  ),
                  color: Colors.red,
                ),
              ],
            ),
            Container(
              height: MediaQuery.of(context).size.height / 1.25,
              child: ListView.builder(
                  itemCount: postmodel.length,
                  itemBuilder: (context, i) {
                    final post = postmodel[i];
                    return Card(
                      color: Colors.green[100],
                      child: Container(
                        padding: EdgeInsets.all(10),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(post.titre,
                                style: TextStyle(
                                    fontSize: 20,
                                    fontWeight: FontWeight.bold)),
                            Divider(),
                            Text(post.detail,
                                style: TextStyle(
                                    fontSize: 5,
                                    fontWeight: FontWeight.bold)),
                            Text("Publier le ;" + post.date_post,
                                style: TextStyle(
                                    fontSize: 5, fontWeight: FontWeight.bold))
                          ],
                        ),
                      ),
                    );
                  }),
            )
          ],
        )));
  }
}

有#PostModel()函数代码:

class PostModel {
  String titre;
  String detail, date_post;
  String user, id_post;
  PostModel({this.titre, this.detail, this.user, this.date_post, this.id_post});

  factory PostModel.fromJson(Map<String, dynamic> j) {
    return PostModel(
        id_post: j["id_post"],
        user: j["id_user"],
        titre: j["title"],
        detail: j["detail"],
        date_post: j["date_post"]);
  }

  Map toMap() {
    return {
      "id_post": id_post,
      "id_user": user,
      "titre": titre,
      "detail": detail
    };
  }
}

这是我经常遇到的错误:

Error: Expected a value of type 'Map<String, dynamic>', but got one of type 'List<dynamic>'
    at Object.throw_ [as throw] (http://localhost:50904/dart_sdk.js:5333:11)
    at Object.castError (http://localhost:50904/dart_sdk.js:5304:15)
    at Object.cast [as as] (http://localhost:50904/dart_sdk.js:5620:17)
    at dart.LegacyType.new.as (http://localhost:50904/dart_sdk.js:7218:60)
    at home._HomeState.new.getDta (http://localhost:50904/packages/mostapha_app/screens/Home/home.dart.lib.js:1072:47)
    at getDta.next (<anonymous>)
    at http://localhost:50904/dart_sdk.js:39031:33
    at _RootZone.runUnary (http://localhost:50904/dart_sdk.js:38888:58)
    at _FutureListener.thenAwait.handleValue (http://localhost:50904/dart_sdk.js:33874:29)
    at handleValueCallback (http://localhost:50904/dart_sdk.js:34434:49)
    at Function._propagateToListeners (http://localhost:50904/dart_sdk.js:34472:17)
    at _Future.new.[_completeWithValue] (http://localhost:50904/dart_sdk.js:34314:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:50904/dart_sdk.js:34337:35)
    at Object._microtaskLoop (http://localhost:50904/dart_sdk.js:39175:13)
    at _startMicrotaskLoop (http://localhost:50904/dart_sdk.js:39181:13)
    at http://localhost:50904/dart_sdk.js:34688:9

请提供任何帮助

1 个答案:

答案 0 :(得分:0)

请提供 API 响应,以便我们提供帮助 在这里,您的 API 为您提供了 jsonEncoded 列表,并且您正在尝试转换为 Map

尝试解码列表

jsonDecode(data);