Home > Mobile >  Encoded List<dynamic> cannot be mapped to TableRow flutter
Encoded List<dynamic> cannot be mapped to TableRow flutter

Time:03-28

I want to show list of maps in the TableRow. The json listMap has the following format without the quotes around the keys and key values:

[
  {
    "item1": "value1",

  },
  {
    "item2": "value2",

  },
  {
    "item3": "value3",

  },

]

I am grabbing this list of objects and the variable listMap contains this format json without quotes.


  Container(
      alignment: Alignment.topLeft,
      child: Padding(
        padding: const EdgeInsets.all(25),
        child: SingleChildScrollView(
          child: Table(
            columnWidths: const {
              0: FixedColumnWidth(50),
              1: FlexColumnWidth(),
            },
            children: (widget.listMap)
                .map((object) {
              return TableRow(children: [
                Container(
                    color: (widget.listMap)
                                    .indexOf(object) %
                                2 ==
                            0
                        ? const Color(0xFF161616)
                        : Colors.grey[800],
                    padding: const EdgeInsets.all(15),
                    child: Text(
                      object['item1'].toString(),
                      style: TextStyle(color: Colors.white),
                    )),
              ]);
            }).toList(),
            border: TableBorder.all(
                width: 1, color: Color(0xFF161616)),
          ),
        ),
      ))

I get the error: 'List' is not a subtype of type 'List' . This is because TableRow` does not recognize the json keys and values without quotes.

How can i resolve this issue?

Edit

So edited the json with quotes because people found it confusing why used the json keys and values without quotes, but that is the format i get from the variable widget.listMap

widget.listMap is the json but without the quotes around the keys and values which is why i get the error: type 'List<dynamic>' is not a subtype of type 'List<TableRow>' Edit

This the code that grabs the json object:

class TestData {
  Future<Map<String, dynamic>> getTestData() async {
    String jsonData =
        await rootBundle.loadString('assets/test_json/test_json1.json');
    Map<String, dynamic> data = jsonDecode(jsonData);
    return data;
  }
}

Edit Code below shows that listMap is passed from another widget and then i make it a List

class AppView extends StatefulWidget {
  final List listMap;
  const AppView({Key? key, required this.listMap}) : super(key: key);

  @override
  _AppBaseState createState() => _AppBaseState();
}

CodePudding user response:

Is your listMap a Map or a String?

If it's a Map, for example something like this:

final listMap = [
  {'item1': 'value1'},
  {'item2': 'value2'},
  {'item3': 'value3'},
];

Then you can use it in the widget by mapping that Map and using object to get an index from listMap.

children: listMap.map((object) {
  final index = listMap.indexOf(object);
  return TableRow(
    children: [
      Container(
        color: index % 2 == 0 ? const Color(0xFF161616) : Colors.grey[800],
        padding: const EdgeInsets.all(15),
        child: Text(
          object['item$index'].toString(),
          style: TextStyle(color: Colors.white),
        ),
      ),
    ],
  );
}).toList(),

If it's a String, for example:

final listJsonString = "[{\"item0\":\"value1\"},{\"item1\":\"value2\"},{\"item2\":\"value3\"}]";

Then you have to decode it from the JSON first:

final parsedListJson = jsonDecode(listJsonString);
final listMap = List<Map<String, dynamic>>.from(parsedListJson.map((i) => Map<String, dynamic>.from(i)));

CodePudding user response:

I tried this and had no errors:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
 List<Map<String,dynamic>> myListMap=[];

  void loadJson() async {
    myListMap= [await TestData().getTestData()];
    setState(() {

    });
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    loadJson();
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:  MyHomePage(listMap: myListMap),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final List<Map<String,dynamic>> listMap;

  const MyHomePage({Key? key, required this.listMap}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return  Container(
        alignment: Alignment.topLeft,
        child: Padding(
          padding: const EdgeInsets.all(25),
          child: SingleChildScrollView(
            child: Table(
              columnWidths: const {
                0: FixedColumnWidth(50),
                1: FlexColumnWidth(),
              },
              children: (widget.listMap)
                  .map((object) {
                return TableRow(children: [
                  Container(
                      color: (widget.listMap)
                          .indexOf(object) %
                          2 ==
                          0
                          ? const Color(0xFF161616)
                          : Colors.grey[800],
                      padding: const EdgeInsets.all(15),
                      child: Text(
                        object['item1'].toString(),
                        style: TextStyle(color: Colors.white),
                      )),
                ]);
              }).toList(),
              border: TableBorder.all(
                  width: 1, color: Color(0xFF161616)),
            ),
          ),
        ));
  }
}


class TestData {
  Future<Map<String, dynamic>> getTestData() async {
    String jsonData =
    await rootBundle.loadString('assets/test_json1.json');
    Map<String, dynamic> data = jsonDecode(jsonData);
    return data;
  }
}

  • Related