How to pass basic auth credentials in API call for a Flutter mobile application?

Assuming that your server expects that the username:password combo will be encode it UTF-8 (see RFC 7617 for more details) then use this:

import 'dart:convert';
    
import 'package:http/http.dart';
    
main() async {
  String username = 'test';
  String password = '123£';
  String basicAuth =
      'Basic ' + base64.encode(utf8.encode('$username:$password'));
  print(basicAuth);
    
  Response r = await get(Uri.parse('https://api.somewhere.io'),
      headers: <String, String>{'authorization': basicAuth});
  print(r.statusCode);
  print(r.body);
}

I know it's late but I am posting this if it can help others.

import 'dart:convert';

var auth = 'Basic '+base64Encode(utf8.encode('$username:$password'));

Future<Response> callAPI(param) async {
    await dio.post('/api/test',
        data: {'param': param},
        options: Options(headers: <String, String>{'authorization': auth})); 
  }

Tags:

Http

Dart

Flutter