promize_sdk 0.1.2 copy "promize_sdk: ^0.1.2" to clipboard
promize_sdk: ^0.1.2 copied to clipboard

A data collection SDK provides an easy way to collect your users data and interests

example/lib/main.dart

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:promize_sdk/core/event_types.dart';
import 'package:promize_sdk/core/models/user.dart';
import 'package:promize_sdk/promize_sdk.dart';

import 'alert.dart';
import 'flavors.dart';

Future<void> runMainApp(Flavor flavor) async {
  WidgetsFlutterBinding.ensureInitialized();
  // await Firebase.initializeApp(
  //   options: DefaultFirebaseOptions.currentPlatform,
  // );
  runApp(MaterialApp(
    debugShowCheckedModeBanner: flavor == Flavor.development,
    home: MyApp(
      flavor: flavor,
    ),
  ));
}

class MyApp extends StatefulWidget {
  final Flavor flavor;

  const MyApp({required this.flavor});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _promizeSdkPlugin = PromizeSdk.instance;

  String token = '';
  EventType? _eventType = EventType.event;
  TextEditingController _nameController = TextEditingController();
  TextEditingController _emailController = TextEditingController();
  TextEditingController _userIdController = TextEditingController();
  TextEditingController _eventNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      setupFirebaseMessaging();
      await _promizeSdkPlugin.initialize(
        apiKey: '{your-api-key}',
        siteId: '{your-site-id}',
        baseUrl: widget.flavor == Flavor.production
            ? '{your-base-url}'
            : '{your-base-url}',
        appVersion: '0.0.1',
      );

      // addEvent();

      //updateUser();
    });
  }

  void createUser({String? name, String? email, String? userId}) {
    _promizeSdkPlugin.createUser(
      user: User(
        name: name ?? "abdelsadek",
        email: email ?? "suhaib.kotb@gmail.com",
        userId: userId ?? "44",
      ),
    );
  }

  void updateUser() {
    _promizeSdkPlugin.createUser(
      user: const User(
        name: "abd elsadek",
        email: "abdelsadek@gmail.com",
        userId: "44",
      ),
    );
  }

  void updateDeviceToken(String? token) {
    if (token == null) return;
    setState(() {
      this.token = token;
    });
    debugPrint(token);
    _promizeSdkPlugin.updateDeviceToken(
      deviceToken: token,
    );
  }

  void addEvent({String? eventName, EventType? eventType}) {
    _promizeSdkPlugin.addEvent(
      eventName: eventName ?? "test Event",
      eventType: eventType ?? EventType.event,
      eventData: {"first_collectd": "data"},
    );
  }

  void setupFirebaseMessaging() async {
    FirebaseMessaging messaging = FirebaseMessaging.instance;
    final fcmToken = await messaging.getToken();
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );
    saveDeviceToken(fcmToken);
    setState(() {
      this.token = fcmToken ?? '';
    });
    debugPrint('User granted permission: ${settings.authorizationStatus}');
    messaging.onTokenRefresh.listen((fcmToken) {
      // Note: This callback is fired at each app startup and whenever a new
      // token is generated.
      updateDeviceToken(fcmToken);
    }).onError((err) {
      debugPrint(err.toString());
    });
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');

      if (message.notification != null) {
        print(
            'Message also contained a notification: ${message.notification?.title ?? ''} - ${message.notification?.body ?? ''}');
      }
      Alert.instance.showNotification(
        context,
        message.notification?.title,
        message.notification?.body,
        () {},
      );
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('A new onMessageOpenedApp event was published!');
      print('Message data: ${message.data}');
      // Alert.instance.showNotification(
      //   context,
      //   message.notification?.title,
      //   message.notification?.body,
      //   () {},
      // );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Promize SDK ${widget.flavor.name}'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Row(
                  children: [
                    Text('FCM Token: '),
                    Flexible(
                        child: SelectableText(
                      token,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    )),
                  ],
                ),
                const SizedBox(height: 10),
                Row(
                  children: [
                    Text('Email: '),
                    Flexible(
                        child: SelectableText(
                      _emailController.text,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    )),
                  ],
                ),
                const SizedBox(height: 10),
                Row(
                  children: [
                    Text('User Id: '),
                    Flexible(
                        child: SelectableText(
                      _userIdController.text,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    )),
                  ],
                ),
                const SizedBox(height: 10),
                TextField(
                  controller: _nameController,
                  decoration: const InputDecoration(
                    hintText: 'Name',
                  ),
                  onChanged: (value) {},
                ),
                const SizedBox(height: 10),
                TextField(
                  controller: _emailController,
                  decoration: const InputDecoration(
                    hintText: 'Email',
                  ),
                  onChanged: (value) {},
                ),
                const SizedBox(height: 10),
                TextField(
                  controller: _userIdController,
                  decoration: const InputDecoration(
                    hintText: 'UserID',
                  ),
                  onChanged: (value) {},
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () {
                    createUser(
                      name: _nameController.text,
                      email: _emailController.text,
                      userId: _userIdController.text,
                    );
                    setState(() {});
                  },
                  child: const Text('Create User'),
                ),
                const SizedBox(height: 30),
                TextField(
                  controller: _eventNameController,
                  decoration: const InputDecoration(
                    hintText: 'Event Name',
                  ),
                  onChanged: (value) {},
                ),
                const SizedBox(height: 16),
                DropdownButton<EventType>(
                    value: _eventType,
                    isExpanded: true,
                    items: EventType.values
                        .map((e) => DropdownMenuItem<EventType>(
                            value: e, child: Text(e.name)))
                        .toList(),
                    onChanged: (value) {
                      setState(() {
                        _eventType = value!;
                      });
                    }),
                const SizedBox(height: 10),
                ElevatedButton(
                  onPressed: () {
                    addEvent(
                      eventName: _eventNameController.text,
                      eventType: _eventType,
                    );
                    setState(() {});
                  },
                  child: const Text('Add Event'),
                ),
                const SizedBox(height: 30),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void saveDeviceToken(String? fcmToken) {
    if (fcmToken == null) return;
    _promizeSdkPlugin.saveDeviceToken(deviceToken: fcmToken);
  }
}