最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

flutter - How to fetch a list<dynamic> from MongoDB and convert that to a list<object> - Stack Overf

programmeradmin2浏览0评论

I am using Flutter, MongoDB, Mongoose, NodeJS and SocketIO.

In MongoDB I am storing a list<object> object, querying the object with model.find() and passing the results back to the client.

But on the client side I am receiving a list<dynamic> object and I don't understand how to convert it to a list<Object> object.

Server-side code

socket.on("event", async() => {
    var objectList =await Model.find();
    socket.emit("event",objectList);
});

Client-side code

function() {
    _socketClient?.on("event",(objectList) { //objectList is a here a list<dynamic>
    List<Object> list = objectList.cast<Object>();
    //Here I am get an exception
    Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'String'
  });
}

I am using Flutter, MongoDB, Mongoose, NodeJS and SocketIO.

In MongoDB I am storing a list<object> object, querying the object with model.find() and passing the results back to the client.

But on the client side I am receiving a list<dynamic> object and I don't understand how to convert it to a list<Object> object.

Server-side code

socket.on("event", async() => {
    var objectList =await Model.find();
    socket.emit("event",objectList);
});

Client-side code

function() {
    _socketClient?.on("event",(objectList) { //objectList is a here a list<dynamic>
    List<Object> list = objectList.cast<Object>();
    //Here I am get an exception
    Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'String'
  });
}
Share Improve this question edited Feb 19 at 6:09 Chait 1,2872 gold badges22 silver badges36 bronze badges asked Feb 14 at 20:58 user29365632user29365632 133 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

To resolve this issue, you need to cast each element of the objectList to the appropriate type instead of trying to cast the entire list at once.

Here's how you can convert the received list of objects to a List in your Flutter client:

function() {  
  _socketClient?.on("event", (objectList) {  
    List<Object> list = [];  
      
    for (var obj in objectList) {  
      list.add(obj as Object);  
    }  
      
    // Now you have a List<Object> containing the objects received from the server  
  });  
}  
发布评论

评论列表(0)

  1. 暂无评论