The dart code I compile is:
import 'dart:js';
import 'package:dio/dio.dart';
final Dio _dio = Dio();
class LoginResponse extends GenericResponse {
String? accessToken;
String? refreshToken;
LoginResponse(statusCode, this.accessToken, this.refreshToken)
: super(statusCode);
}
Future<LoginResponse> login(String phoneNumber, String password, String otp) async {
Response response = await _dio.post(
"https://example.com/token/obtain/",
data: {'phone_number': phoneNumber, 'password': password, 'otp': otp},
options: Options(validateStatus: (status) => status! < 500),
);
return LoginResponse(response.statusCode, response.data['access'], response.data['refresh']);
}
main() => context['loginFromDart'] = login;
I wish to access LoginResponse.accessToken and LoginResponse.refreshToken from the browser console. But still didn't find a way to do it.

You're looking for the
dart:jslibrary.You need to basically use
allowInteropand the@JS()notation.Setup
The
PromiseclassYou define a custom
Promiseclass using the@JSannotation. This is necessary to create a promise instance that can be used from JavaScript to interact with Dart asynchronous code:For your example -
LoginClassDio and request setup
Perform login
The
performLoginfunction wraps the login process in a promise, allowing it to be accessed from JavaScript:Binding
performLoginto JavascriptWindowObject:You use the
setPropertyfunction from thejs_utillibrary to bind theperformLoginfunction to thewindowobject. This makes it accessible from the browser console:Calling the code within the Browser console
You can now use:
Result
Putting it all together
Here's the complete code as a runnable snippet
See also
Origin for this code (Github issue)
Call Dart method from JS in Flutter Web (StackOverflow)
How can I convert various Dart data types to JavaScript for use in a browser? (StackOverflow)