How to get device user agent information in Flutter

Viewed 12450

I'm building a flutter app which needs to send user agent information along with the http request. I'm using http dart package to send requests. How to get user agent string in flutter and use it with http package?

4 Answers

I done it by calling native methods in flutter. First you have to add method channel in android Main Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);

    new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
            new MethodChannel.MethodCallHandler() {
                @Override
                public void onMethodCall(MethodCall call, MethodChannel.Result result) {
                    if (call.method.equals("getUserAgent")) {
                        result.success(System.getProperty("http.agent"));
                    } else {
                        result.notImplemented();
                    }
                }
            });
}

Then getUserAgent() method can be called in flutter like below

Future<String> _getUserAgent() async {
  try {
    return await platform.invokeMethod('getUserAgent');
  } catch (e) {
    return 'Unknown';
  }
}

You can get it in a cross-platform way by using the flutter_user_agent library: https://pub.dev/packages/flutter_user_agent.

import 'package:flutter_user_agent/flutter_user_agent.dart';

...

    String ua = await FlutterUserAgent.getPropertyAsync('userAgent');

this worked for me by using flutter_user_agent library: https://pub.dev/packages/flutter_user_agent as mentioned above

String _userAgent = await FlutterUserAgent.getPropertyAsync('userAgent');

    final _response = await http.get(_url, headers: {
      'Content-Type': 'application/json',
      'Accept-Charset': 'utf-8',
      'User-Agent': '${_userAgent.toLowerCase()}',
    });

Found a library that does it. It would be interesting to look at what the library does, i don't think it's needed to implement a library for that.

https://pub.dartlang.org/packages/user_agent

An example on how you would use it:

main() async {
    app.get('/', (req, res) async {
        var ua = new UserAgent(req.headers.value('user-agent'));

        if (ua.isChrome) {
            res.redirect('/upgrade-your-browser');
            return;
        } else {
            // ...
        }
    });
}

Alternatively, if you want to add a user-agent to the http client, you can do it this way:

Future<http.Response> fetchPost() {
  return http.get(your_url,
    // Send user-agent header to your backend
    headers: {HttpHeaders.userAgentHeader: "your_user_agent"},
  );
}

You can look at HttpHeadersto see the full list of predefined headers, although headers take a map, you could create your own header if you want.

Related