flutter 参数类型“Object?”不能赋给参数类型“Map〈dynamic,dynamic>”

wsewodh2  于 2023-01-14  发布在  Flutter
关注(0)|答案(3)|浏览(161)

我在下面一行中的“snap.snapshot.value”参数上有一个错误“var map = Map〈String,dynamic〉.from(snap.snapshot.value);“。错误为“无法将参数类型”Object?“赋给参数类型”Map〈dynamic,dynamic〉“。“

class _HomePageState extends State<HomePage> {

  List<Posts> postsList = [];

  @override
  void initState() {

    super.initState();

    DatabaseReference postsRef = FirebaseDatabase.instance.reference().child("Posts");

    postsRef.once().then((snap) {

      var map = Map<String, dynamic>.from(snap.snapshot.value); <--- the error is here

      postsList.clear();

      map.forEach((key, value) {
        var values = Map<String,dynamic>.from(map);
        Posts posts = Posts
          (
            values['url'],
            values['descrizione'],
            values['data'],
            values['ora']
        );
        postsList.add(posts);
      });
yzuktlbb

yzuktlbb1#

你会改变一个代码像下面?

var map = Map<String, dynamic>.from(snap.snapshot.value);

Map<String, dynamic> map = snap.snapshot.value as Map<String, dynamic>
mqxuamgl

mqxuamgl2#

这是因为Map.from函数接受了一个Map〈dynamic,dynamic〉,但是你传递的是object,所以要传递相同的值,请使用如下的类型转换:

var map = Map<String, dynamic>.from(snap.snapshot.value as Map<dynamic, dynamic>);
a14dhokn

a14dhokn3#

在你的帖子模型中,你需要移除任何显式的对象转换。例如,从

`Posts.fromMap(Map<String, dynamic> map) {
comments: List<String>.from((map['comments'] as List<String>)) 
}`

`Posts.fromMap(Map<String, dynamic> map) {
comments: List<String>.from((map['comments'] as List)) 
}`

因此它被强制转换为List,不再进一步

相关问题