Home > Mobile >  Flutter, "The method 'map' can't be unconditionally invoked because the receiver
Flutter, "The method 'map' can't be unconditionally invoked because the receiver

Time:10-14

I am getting this error when I am trying to call the .map method on the snapshot.data. I am using an SQLite database.

The code throwing the error is the following:

FutureBuilder(
                future: _alarms,
                builder: (context, snapshot)
                {
                  if(snapshot.hasData){
                  return ListView(
                    children: snapshot.data.map<Widget>((alarms) {
                      return Container(

And I am creating the _alarms list in the initState method:

 @override
  void initState() {
    _alarmHelper.initializeDatabase().then((value) => print('------------dB initialized'));
    _alarms = _alarmHelper.getAlarm();
    super.initState();
  }

And the .getAlarm(), is defined so:

 Future<List<AlarmInfo>> getAlarm() async{
    var result;
    var db = await this.database;

      result = await db?.query(tableName);

     result.forEach((element) { 
      var alarmInfo  = AlarmInfo.fromMap(element);
      alarms.add(alarmInfo);
      }
      );

      return alarms;
  }

I have also tried adding a ?. operator, but then this returns another error which is the .map is not defined for the type object children: snapshot.data?.map<Widget>((alarms) {

Any help is appreciated and if you require any further information feel free to leave a comment.

Thanks :)

CodePudding user response:

I assume it's because you didn't provide a type for the FutureBuilder widget, therefore snapshot.data is from type Object (instead of a list you are expecting there) and the map function does not exist for that.

It should be fixed by writing it like this:

FutureBuilder<List<AlarmInfo>>(
   ...
),

Additionally since data might be null (but you checked it with snapshot.hasData you have to write:

snapshot.data!.map(...)
  • Related