Home > Blockchain >  how to cast other types of key values inside json object other than string to string in dart?
how to cast other types of key values inside json object other than string to string in dart?

Time:03-19

I have a json object where i want to visualize the keys and key values with ListView.builder :

class Items {
  Map<String, dynamic> getItems() {
    String jsonData = '{ "item1": true,"item2": "value2","item3": "value3"}';

    Map<String, dynamic> data = jsonDecode(jsonData);
    return data;
  }
}

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

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

class _AppState extends State<App> {
  @override
  Widget build(BuildContext context) {
    Map<String, dynamic> data = Items().getItems();
    return Scaffold(
      body: ListView.builder(
        itemCount: data.keys.length,
        itemBuilder: (c, index) {
          return ListTile(
            title: Text(
              "Value "   data.values.toList()[index],
              style: TextStyle(color: Colors.white),
            ),
            subtitle: Text(
              "Key "   data.keys.toList()[index],
              style: TextStyle(color: Colors.white),
            ),
          );
        },
      ),
    );
  }
}

And i have inisde the json object inside key item1 a boolean value. And so i get the error type 'bool' is not a subtype of type 'String' .

So i wonder how i can show all types of values (not just boolean) aside from String from the json object inside the ListView.builder without getting the error.

CodePudding user response:

Use data.values.toList()[index].toString();

  • Related