flutter_conscent_plugin 0.1.7 copy "flutter_conscent_plugin: ^0.1.7" to clipboard
flutter_conscent_plugin: ^0.1.7 copied to clipboard

This is a step by step guide for managing Conscent Plugin and its related subclasses.

example/main.dart

import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;
import 'package:flutter_conscent_plugin/ConscentInitializer.dart';
import 'package:flutter_conscent_plugin/Model/APIMode.dart';
import 'package:flutter_conscent_plugin/Model/PaywallViewEvent.dart';
import 'package:flutter_conscent_plugin/Model/embeddedSubscribtion.dart';
import 'package:flutter_conscent_plugin/Model/getUserDetail.dart';
import 'package:flutter_conscent_plugin/Model/loginChallengepost.dart';
import 'package:flutter_conscent_plugin/Model/subscriptionAccess.dart';
import 'package:flutter_conscent_plugin/passesWebviews.dart';
import 'package:fk_user_agent/fk_user_agent.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_conscent_plugin/webview.dart';
import 'package:flutter_conscent_plugin/webviewConscent.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';

var messageBodyData = MessageBody();

// ignore: must_be_immutable
class DefaultSub extends StatefulWidget {
  Function(String) sessionCallback;
  DefaultSub(this.sessionCallback, {Key? key}) : super(key: key);

  @override
  State<DefaultSub> createState() => _MyAppppState();
}

String loginChallengeId = "loginChallengeId";
String sessionId = "sessionId";

class _MyAppppState extends State<DefaultSub> {
  var uuid =
      '${DateTime.now().millisecondsSinceEpoch.toString()}${const Uuid().v4()}';

  var uuids = const Uuid();

  bool visible = false;

  final loginChallengeId = TextEditingController();
  final redirectTo = TextEditingController();

  final clientId = TextEditingController();
  final clientContentId = TextEditingController();
  final sessionId = TextEditingController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      await FkUserAgent.init();
      initPlatformState();
    });

    getPsts();
    if (Platform.isAndroid) {
      messageBodyData.osName = "Android";
    } else if (Platform.isIOS) {
      messageBodyData.osName = "Iphone";
    }
    paywallViewEvent();
  }

//paywallViewEvent
  Future<void> paywallViewEvent() async {
    var uuid =
        '${DateTime.now().millisecondsSinceEpoch.toString()}${const Uuid().v4()}';

    DateFormat dateFormat = DateFormat("yyyy-MM-dd HH:mm:ss");
    String createdAt = dateFormat.format(DateTime.now());

    messageBodyData.id = uuid;
    messageBodyData.createdAt = createdAt;
    messageBodyData.updatedAt = createdAt;
    messageBodyData.deviceType = "Mobile";
    messageBodyData.eventLocation = "PAYWALL";
    messageBodyData.eventType = "VIEW";
    messageBodyData.isCookieBlocked = 0;
    messageBodyData.paywallId = "Default";
    messageBodyData.numOfCta = 2;

    var paywallViewEvent = PaywallViewEvent(messageBody: [messageBodyData]);
    paywallViewEvent.topic = "demoTopic";
  }

//initPlatformState
  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      platformVersion = FkUserAgent.userAgent!;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }
    messageBodyData.userAgent = "${FkUserAgent.webViewUserAgent}";
    messageBodyData.osVersion = "${FkUserAgent.userAgent}";
    messageBodyData.mobileModel = platformVersion;

    if (!mounted) return;
  }

  Object? get filteredProducts => null;

  dynamic dataMains;

  Future<LoginChallengepost> submitDatas(
      String loginChallengeId, String redirectTo) async {
    var response = await http.post(
        Uri.parse('${APIMode.BASE_URL}api/v1/login-challenge'),
        body: {"loginChallengeId": uuids.v1(), "redirectTo": redirectTo});
    if (response.statusCode == 201) {
      dataMains = jsonDecode(response.body);
      var responseString = response.body;
      String loginChallengeId =
          loginChallengepostFromJson(responseString).loginChallengeId;
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('loginID', loginChallengeId);
      return loginChallengepostFromJson(responseString);
    } else {
      throw Exception('Failed to create album.');
    }
  }

  clearData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.clear();
  }

  tryAutoLogin() async {
    var any = await SharedPreferences.getInstance();
    if (!any.containsKey("loginChallengeId")) {
      return false;
    } else {
      return true;
    }
  }

// getPostss
  Future<SubscriptionAccess> getPostss() async {
    var client = http.Client();
    var uri = Uri.parse('${APIMode.BASE_URL}api/v1/subscription/access?');
    var response = await client.get(uri);
    if (response.statusCode == 200) {
      var json = response.body;
      return subscriptionAccessFromJson(json);
    } else {
      throw Exception('Failed to create album.');
    }
  }

  //microPricing Api ----------------------------------------------------------------------------------------------------
  dynamic dataMain;
  getPsts() async {
    var url = Uri.parse(
        '${APIMode.BASE_URL}api/v1/content?clientContentId=${ConscentInitializer.mContentId}&clientId=${ConscentInitializer.mClientId}');
    var response = await http.get(url);
    if (response.statusCode == 200) {
      dataMain = jsonDecode(response.body);
      setState(() {});
    } else {
      throw Exception('Failed to load album');
    }
  }

// API get User Detail get
  Future<GetUserDetail> getPst() async {
    var client = http.Client();
    var uri = Uri.parse(
        '${APIMode.BASE_URL}api/v1/user/62c561a6f8f5315114da9f33?clientId=${ConscentInitializer.mClientId}');
    var response = await client.get(uri);
    if (response.statusCode == 200) {
      var json = response.body;
      return getUserDetailFromJson(json);
    } else {
      throw Exception('Failed to create album.');
    }
  }

//API logout post
  @override
  Widget build(BuildContext context) {
    loginChallengeId.text = 'uuid';
    redirectTo.text = '';

    clientId.text = '5f92a62013332e0f667794dc';
    clientContentId.text = 'Client-Story-Id-1';

    // var data;
    // bool isPressed = false;
    // var toShowSubscriberView = true;

    return SafeArea(
      child: Scaffold(
        body: Center(
          child: Card(
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  const ListTile(
                    tileColor: Color.fromRGBO(240, 240, 240, 1.0),
                    title: Text(
                      'Continue Reading ...',
                      textAlign: TextAlign.center,
                    ),
                  ),

                  ListTile(
                    title: Text(
                      dataMain == null
                          ? ""
                          : dataMain["paywallCustomization"]
                                  ["micropaymentDisplaytext"]
                              .toString(),
                      textAlign: TextAlign.center,
                    ),
                  ),

                  ListTile(
                    title: Text(
                      dataMain == null
                          ? ""
                          // ignore: prefer_interpolation_to_compose_strings
                          : "${"Pay " + dataMain["currencySymbol"]}${dataMain["price"]} to read now",
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                          fontSize: 22, fontWeight: FontWeight.bold),
                    ),
                  ),

                  ElevatedButton(
                    onPressed: () {
                      submitDatas(loginChallengeId.text, redirectTo.text)
                          .then((value) {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => const WebViewApp()),
                        ).then((value) {
                          if (value != null) {
                            dynamic response = value['response'];
                            widget.sessionCallback(response);
                          }
                        });
                      });
                    },
                    style: ElevatedButton.styleFrom(
                      shape: const StadiumBorder(),
                      // ignore: deprecated_member_use
                      primary: const Color.fromRGBO(245, 194, 203, 1.0),
                      minimumSize: const Size(240, 50),
                    ),
                    child:
                        const Text('Read Now', style: TextStyle(fontSize: 20)),
                  ),

                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      const Text('Already Purchased?',
                          style: TextStyle(
                              fontSize: 16, fontWeight: FontWeight.bold)),
                      TextButton(
                        child: const Text(
                          'Log into Conscent',
                          style: TextStyle(
                              fontSize: 16,
                              color: Color.fromRGBO(245, 194, 203, 1.0)),
                        ),
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const WebViewApp(),
                              settings: const RouteSettings(
                                arguments: EmbeddedSubscribtion,
                              ),
                            ),
                          );
                        },
                      ),
                    ],
                  ),

                  const ListTile(
                    title: Text(
                      'Onces paid this story is free for 30 Days',
                      textAlign: TextAlign.center,
                    ),
                  ),

                  const ListTile(
                    title: Text(
                      '------------------  OR  ------------------',
                      textAlign: TextAlign.center,
                    ),
                  ),

//Hide Function
                  Visibility(
                      visible: dataMain == null
                          ? false
                          : dataMain["validPass"] == null
                              ? false
                              : true,
                      child: Column(
                        children: [
                          ListTile(
                            title: Text(dataMain != null &&
                                    dataMain["validPass"] == null
                                ? ''
                                : ''),
                            subtitle: Text(
                              dataMain == null
                                  ? ""
                                  : "${dataMain["validPass"] == null ? 'No hrs' : dataMain["validPass"]['duration'] ?? 'No data'} - hrs unlimited access to premium content",
                              textAlign: TextAlign.center,
                              style: const TextStyle(
                                  fontSize: 16, fontWeight: FontWeight.bold),
                            ),
                          ),
                          ElevatedButton(
                            onPressed: () {
                              submitDatas(
                                      loginChallengeId.text, redirectTo.text)
                                  .then((value) {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          const WebViewAppsss()),
                                ).then((value) {
                                  if (value != null) {
                                    dynamic response = value['response'];
                                    widget.sessionCallback(response);
                                  }
                                });
                              });
                            },
                            style: ElevatedButton.styleFrom(
                                minimumSize: const Size(240, 50),
                                shape: const StadiumBorder(),
                                // ignore: deprecated_member_use
                                primary: Colors.white,
                                side: const BorderSide(
                                    width: 2.0, color: Colors.black)),
                            child: Text(
                                'Buy a pass for ₹ ${dataMain != null && dataMain["validPass"] != null ? dataMain["validPass"]["price"].toString() : ""}',
                                style: const TextStyle(
                                    fontSize: 20,
                                    color: Colors.black,
                                    fontWeight: FontWeight.bold)),
                          ),
                          const ListTile(
                            title: Text(
                              '------------------  OR  ------------------',
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ],
                      )),

                  Visibility(
                      visible: dataMain == null
                          ? false
                          : dataMain["subscriptionsExist"] == false
                              ? false
                              : true,
                      child: Column(
                        children: [
                          ListTile(
                            title: Text(dataMain != null &&
                                    dataMain["subscriptionsExist"] == false
                                ? ''
                                : ''),
                            subtitle: Text(
                              dataMain == null
                                  ? ""
                                  : "${dataMain["subscriptionsExist"] == false ? 'No hrs' : dataMain["paywallCustomization"]['subscriptionTitle'] ?? 'No data'} ",
                              textAlign: TextAlign.center,
                              style: const TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.black),
                            ),
                          ),
                          ListTile(
                            title: Text(
                              dataMain == null
                                  ? ""
                                  : dataMain["paywallCustomization"]
                                      ["subscriptionText"],
                              textAlign: TextAlign.center,
                            ),
                          ),
                          ElevatedButton(
                            onPressed: () {
                              submitDatas(
                                      loginChallengeId.text, redirectTo.text)
                                  .then((value) {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          const WebViewAppss()),
                                ).then((value) {
                                  if (value != null) {
                                    dynamic response = value['response'];
                                    widget.sessionCallback(response);
                                  }
                                });
                              });
                            },
                            style: ElevatedButton.styleFrom(
                                minimumSize: const Size(240, 50),
                                shape: const StadiumBorder(),
                                // ignore: deprecated_member_use
                                primary: Colors.white,
                                side: const BorderSide(
                                    width: 2.0,
                                    color: Color.fromRGBO(245, 194, 203, 1.0))),
                            child: const Text('Subscribe Now',
                                style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                    color: Color.fromRGBO(245, 194, 203, 1.0))),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              const Text('Already a Subscriber?',
                                  style: TextStyle(
                                      fontSize: 15,
                                      color: Colors.black,
                                      fontWeight: FontWeight.bold)),
                              TextButton(
                                child: const Text(
                                  'Sign In',
                                  style: TextStyle(
                                      fontSize: 15,
                                      color:
                                          Color.fromRGBO(245, 194, 203, 1.0)),
                                ),
                                onPressed: () {},
                              ),
                            ],
                          ),
                        ],
                      )),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
1
likes
0
pub points
56%
popularity

Publisher

unverified uploader

This is a step by step guide for managing Conscent Plugin and its related subclasses.

Homepage

License

unknown (LICENSE)

Dependencies

fk_user_agent, flutter, flutter_web_plugins, get, http, intl, liquid_pull_to_refresh, pull_to_refresh, shared_preferences, shared_preferences_web, uuid, webview_flutter

More

Packages that depend on flutter_conscent_plugin