Basic HTTP Auth with Flutter the right way

Within a Flutter app, I just tried to create a POST request to an REST API backend that requires HTTP Basic Auth using this piece of code that I have found on Stackoverflow due to lack of documentation.

String username = 'test';
String password = '123£';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));

Response r = await get('',
headers: {'authorization': basicAuth});

Since my abstraction required a header that was prebuilt somewhere else, I created it this way:

Map headers = {
'content-type': 'application/json',
'accept': 'application/json',
'authorization': basicAuth

However, somewhere within the POST request the following exception was thrown:

_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>' }, event: LoginButtonPressed { username: futzi, password: futz }, nextState: LoginLoading }

Turned out, the Map has do be created with real type hinting:

Map<String, String> headers = {
'content-type': 'application/json',
'accept': 'application/json',
'authorization': basicAuth

This works :)

Ethereum advocate * Full Stack Developer * CEO @ & CTO & Co-Founder @

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store