skip to Main Content

I’m coding the class

class _DashboardState extends State
with SingleTickerProviderStateMixin {
late Future _summaryData;
late Future<List> _chartData;

  @override
  initState() {
    super.initState();
    Future<Map> data = fetchData();
    _summaryData= data['summaryData']; // ERROR HERE
    _chartData= data['chartData']; // ERROR HERE
  }

  Future<Map> fetchData() async {
    ...
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _summaryData,
      builder: ...);
  }

but I face an error The operator '[]' isn't defined for the type 'Future<Map<dynamic, dynamic>>'. Try defining the operator '[]'..

Please tell me the reason and how to solve? thank you!

2

Answers


  1. The issue here is that you are trying to access summaryData and chartData from a Future<Map> and not a Map. In your fetchData() function, make it so that you return Map and not a Future<Map> like so:

    Map fetchData() async {
     return await fetchDataAPICall(); /// Whatever way you are fetching the data
    }
    

    This should return you a Map within which you should be able to access your required data.

    Happy Coding 🙂

    Login or Signup to reply.
  2. change your code to the following.

      @override
      initState() {
        super.initState();
        getData();
      }
    
    void getData()async{
    Future<Map> data = await fetchData();
        _summaryData= data['summaryData']; // ERROR FIX
        _chartData= data['chartData']; // ERROR FIX
    }
    
      Future<Map> fetchData() async {
        ...
      }
    
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
          future: _summaryData,
          builder: ...);
      }
    

    since await cannot be added to init method we create a separate method and mark it async to wait for the api call data.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search