appmate_flutter 0.0.2 copy "appmate_flutter: ^0.0.2" to clipboard
appmate_flutter: ^0.0.2 copied to clipboard

outdated

Appmate flutter plugin project.

example/lib/main.dart

import 'dart:developer';
import 'dart:io';

import 'package:appmate_flutter_example/settings.dart';
import 'package:appmate_flutter_example/user_id_relation.dart';
import 'package:appmate_flutter_example/util.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:appmate_flutter/PurchaseClient.dart';
import 'package:appmate_flutter/models.dart';
import 'package:flutter/cupertino.dart';

import 'purchase.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MaterialApp(
    home: ProductList(),
  ));
}

class ProductList extends StatefulWidget {
  const ProductList({Key? key}) : super(key: key);

  @override
  _ProductListState createState() => _ProductListState();
}

class _ProductListState extends State<ProductList> {
  List<Product> _products = [];
  String _environment = "";

  final _biggerFont = const TextStyle(fontSize: 18);

  @override
  void initState() {
    super.initState();
    PurchaseClient.setApiKey("UxflVlHCTmyKqpDle24SaA");
    PurchaseClient.setSandboxActive(true);
    setEnvironment();
    //AppmateFlutter.setUserId("fatih1905");
  }

  void setEnvironment() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      var env = prefs.getString('_environment');
      _environment = (env != null && env.length > 0) ? env : "prod";
    });
  }

  Future<void> getProducts() async {
    setState(() {
      _products = [];
    });

    List<Product> products = [];
    try {
      ProductsResponse response = await PurchaseClient.getProducts();
      if (response.error != null) {
        Util.showDialog(context, response.error!.message ?? "Unknown Error");
      } else {
        products = response.products ?? [];
      }
    } on PlatformException {}

    if (!mounted) return;

    setState(() {
      _products = products;
    });
  }

  void showProductsWithTypeAlert() {
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
          title: const Text('Get Products With Type'),
          message: const Text('Select Product Type'),
          actions: <Widget>[
            CupertinoActionSheetAction(
              child: const Text('Consumable'),
              onPressed: () {
                getProductsWithType("0");
                Navigator.pop(context, '0');
              },
            ),
            CupertinoActionSheetAction(
              child: const Text('Nonconsumable'),
              onPressed: () {
                getProductsWithType("1");
                Navigator.pop(context, '1');
              },
            ),
            CupertinoActionSheetAction(
              child: const Text('Subscription'),
              onPressed: () {
                getProductsWithType("2");
                Navigator.pop(context, '2');
              },
            )
          ],
          cancelButton: CupertinoActionSheetAction(
            child: const Text('Cancel'),
            isDefaultAction: true,
            onPressed: () {
              Navigator.pop(context, 'Cancel');
            },
          )),
    );
  }

  Future<void> getProductsWithType(String type) async {
    List<Product> products = [];
    try {
      ProductsResponse response = await PurchaseClient.getProductsWithType(type);
      if (response.error != null) {
        Util.showDialog(context, response.error!.message ?? "Unknown Error");
      } else {
        products = response.products ?? [];
      }
    } on PlatformException {}

    if (!mounted) return;

    setState(() {
      _products = products;
    });
  }

  void showProductsByIdAlert() {
    TextEditingController _productIdField = TextEditingController();

    showCupertinoDialog(
      context: context,
      builder: (BuildContext context) => CupertinoAlertDialog(
          title: const Text('Get Product(s) By Id'),
          content: Column(children: [
            Text(
                "Enter Ids, you can seperate them with commas. ie: test_consumable,test_non_consumable"),
            CupertinoTextField(controller: _productIdField)
          ]),
          actions: <Widget>[
            CupertinoActionSheetAction(
              child: const Text('Cancel'),
              onPressed: () {
                Navigator.pop(context, 'Cancel');
              },
            ),
            CupertinoActionSheetAction(
              child: const Text('Get'),
              onPressed: () {
                getProductsWithIdList(_productIdField.text.split(","));
                Navigator.pop(context, '0');
              },
            )
          ]),
    );
  }

  void isProductPurchased() {
    TextEditingController _productIdField = TextEditingController();

    showCupertinoDialog(
      context: context,
      builder: (BuildContext context) => CupertinoAlertDialog(
          title: const Text('is Product Purchased'),
          content: Column(children: [
            Text(
                "Enter Product Id, ie: test_consumable"),
            CupertinoTextField(controller: _productIdField)
          ]),
          actions: <Widget>[
            CupertinoActionSheetAction(
              child: const Text('Cancel'),
              onPressed: () {
                Navigator.pop(context, 'Cancel');
              },
            ),
            CupertinoActionSheetAction(
              child: const Text('Get'),
              onPressed: () async {
                BaseResponse response = await PurchaseClient.isProductPurchased(_productIdField.text);
                if (response.error != null) {
                  Util.showDialog(context, response.error!.message ?? "Unknown Error");
                } else {
                  Util.showDialog(context, response.success ? "Product Purchased" : "Product Not Purchased");
                }
              },
            )
          ]),
    );
  }

  Future<void> getProductsWithIdList(List<String> ids) async {
    List<Product> products = [];
    try {
      ProductsResponse response = await PurchaseClient.getProductsWithIdList(ids);
      if (response.error != null) {
        Util.showDialog(context, response.error!.message ?? "Unknown Error");
      } else {
        products = response.products ?? [];
      }
    } on PlatformException {}

    if (!mounted) return;

    setState(() {
      _products = products;
    });
  }

  Future<void> makePurchase(Product product) async {
    MakePurchaseResponse response;
    try {
      response = await PurchaseClient.makePurchase(product);
      if (response.error != null) {
        Util.showDialog(context, response.error!.message ?? "Unknown Error");
      } else {
        Util.showDialog(context, "Purchase success");
      }
    } on PlatformException {}

    if (!mounted) return;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        title: Text('AppMate - ' + _environment),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.settings,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => Settings()),
              ).then((completion){
                setEnvironment();
              });
            },
          ),
          IconButton(
            icon: Icon(
              Icons.supervised_user_circle,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => UserIdRelation()),
              );
            },
          ),
          IconButton(
            icon: Icon(
              Icons.history,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => PurchaseList()),
              );
            },
          )
        ],
        centerTitle: false,
        backgroundColor: Colors.redAccent,
      ),
      body: SingleChildScrollView(child: _buildProducts()),
    );
  }

  Widget _buildProducts() {
    return Column(
      children: [
        TextButton(
          onPressed: () {
            getProducts();
          },
          child: Text('Get Products'),
        ),
        TextButton(
          onPressed: () {
            showProductsWithTypeAlert();
          },
          child: Text('Get Products With Type'),
        ),
        TextButton(
          onPressed: () {
            showProductsByIdAlert();
          },
          child: Text('Get Products By Id'),
        ),TextButton(
          onPressed: () {
            isProductPurchased();
          },
          child: Text('is Product Purchased'),
        ),
        ListView.builder(
            itemCount: _products.length * 2,
            padding: const EdgeInsets.all(10),
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (BuildContext _context, int i) {
              if (i.isOdd) {
                return Divider();
              }
              final int index = i ~/ 2;
              if (index >= _products.length) {
                return Divider();
              }
              return _buildRow(_products[index]);
            })
      ],
    );
  }

  Widget _buildRow(Product p) {
    return ListTile(
      title: Text(
        p.productLocales![0].productName!,
        style: _biggerFont,
      ),
      subtitle: Text(p.productId!),
      trailing: Text(
        (p.price()) +
            ' ' +
            p.currency(),
        style: _biggerFont,
      ),
      onTap: () {
        makePurchase(p);
      },
    );
  }
}
0
likes
0
pub points
0%
popularity

Publisher

unverified uploader

Appmate flutter plugin project.

Homepage

License

unknown (LICENSE)

Dependencies

flutter

More

Packages that depend on appmate_flutter