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);
}

Leave a Comment

tech