How iterate List<Object> and put data to Text widget?

Viewed 33

I am trying to put data from WebSockets events to my UI, I got the list of maps and I already know how to work with the type of data, but it doesn't work in this case.

I got data this data from events [{warpedBox: [604.3993, 290.7302, 1106.364, 290.7302, 1106.364, 530.2628, 604.3993, 530.2628],name: Cats, date: 2022-09-05T09:01:11.9003992+03:00,additionInfo: Розыск,baseName: testBasename, imageGuid: 00000000-0000-0000-0000-000000000000}]

I can't get a name from this array of data, so how can I achieve this goal?

Future<List> fetchAnimal() async {
    final hubConnection = HubConnectionBuilder()
        .withUrl(
          'securelink',
          options: httpConnectionOptions,
        )
        .build();
    await hubConnection.start();
    List animals= [];
    int? index;
    hubConnection.on('Animal', (arguments) async {
      // print(arguments);
      animals = arguments as List;
     
    });
  
    hubConnection.onclose(({error}) {
      print(error);
    });
    print(animals);
    return animals;
  }

The problem is: that it returns empty lists, or Bad range error if I use index. But in the console, it returns the list above.

it returns me List<Object>? how can I use it in ui?

my future builder:

 body: FutureBuilder<List<Object>?>(
          future: Animal().fetchAnimal(),
          builder: (context, snapshot) {
            print(snapshot.data);
            return Column(
              children: [Text(snapshot.data ?? 'nothing')],
            );
          }),
1 Answers

change your FutureBuilder to this:

FutureBuilder<List<Object>?>(
      future: Animal().fetchAnimal(),
      builder: (context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return Text('Loading....');
          default:
            if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else {
              List<Object> data = snapshot.data ?? [];

              return ListView.builder(
                itemBuilder: (context, index) {
                  return Column(children: [
                    Text(data[index]['name'] ?? ""),
                  ]);
                },
                itemCount: data.length,
              );
            }
        }
      },
    )
Related