Search code examples
flutterdartlistviewhashmap

RangeError (index): Invalid value: Valid value range is empty: 0 in List Map


In my app, I would like to have a listView with pie chart. This is the pie_chart library I'm using.

But I get error in List<Map<String,double>>.

List<Map<String, double>> map = List<Map<String, double>>();

 ListView.builder(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: data.length,
          itemBuilder: (context, index) {
            var item = data[index];
            map[index].putIfAbsent("< 1 Weeks ago>", () => (2.0));
            return PieChart(
                     ...
                dataMap: map[index],
                     ...
            )
    }

Error

RangeError (index): Invalid value: Valid value range is empty: 0

The error pointed to map[index].putIfAbsent("< 1 Weeks ago>", () => (2.0));. What is wrong here?


Solution

  • To add each of the elements from data and add them to map i did this:

      @override
      Widget build(BuildContext context) {
        List map = [];
    
        List data = [
          {'entry_1': 1},
          {'entry_2': 2},
          {'entry_3': 3}
        ];
    
        return MaterialApp(
          title: MyApp._title,
          home: Scaffold(
            body: ListView.builder(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemCount: data.length,
              itemBuilder: (context, index) {
                var item = data[index];
                map.add(item);
                return Container(
                  height: 100,
                  child: Text('Entry: ${map[index]}'),
                );
              },
            ),
          ),
        );
      }
    

    this takes the list of maps "data", grabs each value and add it to the list "map" and then builds a list of containers with a text widget containing the corresponding entry that map took from data