MaxuwkaPlus
MaxuwkaPlus

Reputation: 37

_TypeError (type '_Map<String, dynamic>' is not a subtype of type 'List<dynamic>')

I am trying to build an app to visualize JSON data into table after the authentication, that i'm getting from the REST API by using http.dart

I have made a home_screen.dart to visualize it, but i'm stuck with this error

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'auth_service.dart';
import 'login_screen.dart';

class HomePage extends StatelessWidget {
  final AuthService _authService = AuthService();
  static const String apiUrl = 'my_api_url';

  HomePage({super.key});

  Future<List<Map<String, dynamic>>> fetchData() async {
    final token = await _authService.getToken();

    final response = await http.get(
      Uri.parse('$apiUrl/table'),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $token',
      },
    );

    if (response.statusCode == 200) {
      final List<dynamic> data = jsonDecode(response.body);
      return List<Map<String, dynamic>>.from(data);
    } else {
      throw Exception('Failed to load data');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Home Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FutureBuilder(
              future: fetchData(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  if (snapshot.hasError) {
                    return Text('Error: ${snapshot.error}');
                  } else {
                    List<Map<String, dynamic>> data =
                        snapshot.data as List<Map<String, dynamic>>;
                    return DataTable(
                      columns: const [
                        DataColumn(label: Text('ID')),
                        DataColumn(label: Text('Username')),
                        DataColumn(label: Text('Town')),
                        DataColumn(label: Text('Priority')),
                      ],
                      rows: data
                          .map(
                            (row) => DataRow(
                              cells: [
                                DataCell(Text(row['id'].toString())),
                                DataCell(Text(row['username'])),
                                DataCell(Text(row['town'])),
                                DataCell(Text(row['priority'])),
                              ],
                            ),
                          )
                          .toList(),
                    );
                  }
                } else {
                  return const CircularProgressIndicator();
                }
              },
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                await _authService.logout();
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(builder: (context) => const LoginPage()),
                );
              },
              child: const Text('Logout'),
            ),
          ],
        ),
      ),
    );
  }
}

next is an example of the JSON response.body, that i'm getting(i need just id,town, username,priority)

{
            "id": 104645,
            "area": {
                "id": 192,
                "depth": 4,
            },
            "workflow": {
                "id": 4,
                "name": "processing"
            },
            "state": {
                "id": 2,
                "name": "In work",
            },
            "workObject": {
                "type": "MeterPoint",
                "id": 427840,
                "consumingFacility": {
                    "id": 107303,
                    "address": {
                        "town": "New York"
                    },
                    "coordinates": null
                },
            },
            "assignee": {
                "id": 865,
                "fullName": "John Martins"
            },
            "coordinator": {
                "id": 804,
                "username": "sfr-es-martinsons",
            },
            "priority": 3
        }

Could you help me to resolve this trouble I'm just started to learn dart and this trouble for me looks like impossible to resolve

Upvotes: 0

Views: 58

Answers (1)

Dewa Prabawa
Dewa Prabawa

Reputation: 772

Your return expects a List<Map<String, dynamic>> which you need to use map function.

 if (response.statusCode == 200) {
        final List<dynamic> responseData = jsonDecode(response.body);
        List<Map<String, dynamic>> data = responseData.map((item) {
          return {
            'id': item['id'],
            'town': item['workObject']['consumingFacility']['address']['town'],
            'username': item['coordinator']['username'],
            'priority': item['priority'],
          };
        }).toList();
    
        return data;
      } else {
        throw Exception('Failed to load data');
      }

Upvotes: 0

Related Questions