datadome_flutter_dio 2.2.0 copy "datadome_flutter_dio: ^2.2.0" to clipboard
datadome_flutter_dio: ^2.2.0 copied to clipboard

A DataDome integration for Flutter - Dio Integration

example/lib/main.dart

import 'package:datadome_flutter_dio/datadome_logger.dart';
import 'package:datadome_flutter_dio/tracking/gesture_detection.dart';
import 'package:datadome_flutter_dio_example/webview_page.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:datadome_flutter_dio/datadome_interceptor.dart';

import 'package:dio/dio.dart';
import 'package:datadome_flutter_dio_example/datadome_secrets.dart';

import 'globals.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
  }

  /// Sends a Dio request to a protected endpoint with a `DataDomeInterceptor` instance.
  /// The interceptor will evaluate the response and show a captcha if the request has been blocked by DataDome.
  /// [datadome_client_key] is the client-side key you can get from your dashboard. You can add it in the `datadome_secrets.dart` file from this example.
  /// [test_url] is the protected endpoint you call. You can add it in the `datadome_secrets.dart` file from this example.
  Future<void> sendRequest() async {
    var dio = Dio();
    DataDomeLogger.setLogLevel(LogLevel.info);
    if (datadome_client_key.trim().isEmpty || test_url.trim().isEmpty) {
      DataDomeLogger.error(
          "Please set your client-side key for DataDome and a protected URL for testing in the datadome_secrets.dart file");
      return;
    }
    dataDomeInterceptor =
        DataDomeInterceptor(datadome_client_key, dio, context);
    dio.interceptors.add(dataDomeInterceptor);
    try {
      var response = await dio.get(test_url,
          options: Options(headers: {
            'User-Agent': 'BLOCKUA',
            'Accept': 'application/json'
          }));
      print(response);
    } catch (e) {
      print(e);
    }
  }

  /// If you need to handle the captcha display and dismissal yourself, you can use
  /// the manual interception mode: you will have to implement your own callback functions for both captcha display and dismissal.
  /// [datadome_client_key] is the client-side key you can get from your dashboard. You can add it in the `datadome_secrets.dart` file from this example.
  /// [test_url] is the protected endpoint you call. You can add it in the `datadome_secrets.dart` file from this example.
  Future<void> sendRequestWithManualMode() async {
    var dio = Dio();
    DataDomeLogger.setLogLevel(LogLevel.info);
    if (datadome_client_key.trim().isEmpty || test_url.trim().isEmpty) {
      DataDomeLogger.error(
          "Please set your client-side key for DataDome and a protected URL for testing in the datadome_secrets.dart file");
      return;
    }
    dataDomeInterceptor =
        DataDomeInterceptor.withCallback(datadome_client_key, dio, (widget) {
      displayCaptcha(widget);
    }, () {
      dismissCaptcha();
    });
    dio.interceptors.add(dataDomeInterceptor);
    try {
      var response = await dio.get(test_url,
          options: Options(headers: {
            'User-Agent': 'BLOCKUA',
            'Accept': 'application/json'
          }));
      print(response);
    } catch (e) {
      print(e);
    }
  }

  /// example of captcha display callback function
  void displayCaptcha(Widget view) {
    showGeneralDialog(
      context: context,
      barrierDismissible: false,
      pageBuilder: (context, __, ___) {
        return view;
      },
    );
  }

  /// example of captcha dismiss callback function
  void dismissCaptcha() {
    Navigator.pop(context);
  }

  /// print stored DataDome cookie value
  void printCookieValue() async {
    String value = await dataDomeInterceptor.getDataDomeCookie();
    print("DataDome cookie value: " + value);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: GestureDetection(
          child: Scaffold(
              appBar: AppBar(
                title: const Text('DataDome example app'),
              ),
              body: Center(
                  child: Column(children: <Widget>[
                Container(
                    margin:
                        EdgeInsets.only(left: 25, top: 100, right: 25, bottom: 100),
                    child: Column(children: [
                      Text("Built-in interception"),
                      MaterialButton(
                        child: Text(
                          'Send Request',
                          style: TextStyle(fontSize: 20.0),
                        ),
                        color: Colors.blueAccent,
                        textColor: Colors.white,
                        onPressed: () {
                          sendRequest();
                        },
                      ),
                    ])),
                Container(
                  margin: EdgeInsets.all(25),
                  child: Column(children: [
                    Text("Manual interception"),
                    MaterialButton(
                      child: Text(
                        'Send Request',
                        style: TextStyle(fontSize: 20.0),
                      ),
                      color: Colors.black26,
                      textColor: Colors.white,
                      onPressed: () {
                        sendRequestWithManualMode();
                      },
                    ),
                  ]),
                ),
                Container(
                  margin: EdgeInsets.all(25),
                  child: Column(children: [
                    Text("Open webview page"),
                    MaterialButton(
                      child: Text(
                        'Open webview',
                        style: TextStyle(fontSize: 20.0),
                      ),
                      color: Colors.blueGrey,
                      textColor: Colors.white,
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => WebviewPage()),
                        );
                      },
                    ),
                  ]),
                ),
                Container(
                  margin: EdgeInsets.all(25),
                  child: Column(children: [
                    Text("Get DataDome cookie value"),
                    MaterialButton(
                        child: Text(
                          'Get cookie',
                          style: TextStyle(fontSize: 20.0),
                        ),
                        color: Colors.blueGrey,
                        textColor: Colors.white,
                        onPressed: () {
                          printCookieValue();
                        })
                  ]),
                ),
              ]))),
        )
    );
  }
}