const headers map in NetworkTileProvider crash the TileLayer (Cannot modify unmodifiable map)
What is the bug?
I ran into this while adding some custom headers to the tile requests, I think its easy to miss so wanted to report it.
If you give a const map to NetworkTileProvider(headers: ...), the app compiles fine and analyzer says nothing, but when the map page opens it throws:
Unsupported operation: Cannot modify unmodifiable map
It comes from the TileLayer constructor, it calls tileProvider.headers.putIfAbsent('User-Agent', ...) and of course a const map cant be modified. Without the const it works, and I can see the User-Agent gets added into my own map:
{X-Some-Header: value, User-Agent: flutter_map (com.example.app)}
I know the docs on the TileProvider constructor says the headers map "must not be constant", but honestly I only found that after getting the error. The headers are just static strings so its very normal to write const there, and lints like prefer_const_literals_to_create_immutables kind of push you to add it.
Happens on all non-web platforms I think, I tested on Android. flutter_map 8.3.2, Flutter 3.47.9 (stable)
Kind of related: #1292 had the same error but it was from the default headers map in custom TileProvider subclasses, that one got fixed by making the default mutable. And #1307 explains why headers needs to be mutable. But passing your own const map still hit it.
How can we reproduce it?
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
void main() => runApp(const MaterialApp(home: MapPage()));
class MapPage extends StatelessWidget {
const MapPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: FlutterMap(
options: const MapOptions(),
children: [
TileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'com.example.app',
tileProvider: NetworkTileProvider(
headers: const {'X-Some-Header': 'value'}, // remove const and it works
),
),
],
),
);
}
}
Run it on Android/iOS/desktop, it throws as soon as the map is built.
Do you have a potential solution?
What if TileProvider just copies the map in the constructor?
TileProvider({Map<String, String>? headers}) : headers = {...?headers};
Then TileLayer always change its own copy and it doesnt matter what user passes. Or if you dont want that, at least a better error message saying the map can't be const would help a lot. Happy to open a PR if you like the copy idea.