flutterfluttermap

GeoJSON displayed when checkbox is checked in flutter_map


Being new in the flutter world, I am wondering if someone can give me a hand with the following issue. I want to display a GeoJSON after a checkbox is checked but not sure how to call it:

CheckboxListTile(
  title: Text(
  'Test query',
  ),
  value: _isCheckedPoMt,
  onChanged: (bool? newValue) {
    setState(() {
      _isCheckedPoMt = newValue ?? false;
    });
  },
),

where:

       //====================
        // issue starts here =
        //====================
        if (_isCheckedPoMt) {
          GeoJsonLayer.asset(
            'assets/data/all.geojson',
            styleDefaults: GeoJsonStyleDefaults(
              strokeColor: Colors.black,
              strokeOpacity: 0.5,
              strokeWidth: 2.5,
           ),
         ),
        }
        //========================

It seems that I am missing something in the if (_isCheckedPoMt) { part because it keeps saying The element type 'Set<GeoJsonLayer>' can't be assigned to the list type 'Widget'.dartlist_element_type_not_assignable.

What would it be wrong here? Any help is appreciated,


Solution

  • As mentioned by Omi Shah, using curly braces {} inside a list can unintentionally create a Set rather than a adding the item directly. To fix the issue, you should avoid placing the curly braces around the object/widget inside a conditional statement. Instead, directly insert the widget using an inline if statement without additional braces, like this:

    body: Stack(
      children: [
        Center(
          child: FlutterMap(
            options: MapOptions(
              initialCenter: const LatLng(10, 33.5),
              initialZoom: 6.3,
            ),
            children: [
              TileLayer(
                tileProvider: NetworkTileProvider(
                  headers: {
                    'User-Agent': 'flutter_map/1.1.1',
                  },
                ),
                urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
              ),
              GeoJsonLayer.asset(
                'assets/data/line1.geojson',
                styleDefaults: GeoJsonStyleDefaults(
                  strokeColor: Colors.red,
                  strokeOpacity: 0.5,
                  strokeWidth: 2.5,
                ),
              ),
              if (_isCheckedPoMt)
                GeoJsonLayer.asset(
                  'assets/data/all.geojson',
                  styleDefaults: GeoJsonStyleDefaults(
                    strokeColor: Colors.black,
                    strokeOpacity: 0.5,
                    strokeWidth: 2.5,
                  ),
                ),
            ],
          ),
        ),
      ],
    )