Hagen Hübel

Aug 20, 2019

1 min read

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('https://api.somewhere.io',
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 * CTO @ https://token-forge.io & CTO & Co-Founder @ Zizzle.io

Love podcasts or audiobooks? Learn on the go with our new app.