Flutter消息推送插件chabok_flutter的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter消息推送插件chabok_flutter的使用


Chabok Push Client for Flutter

pub package

Flutter包装器用于Chabok库。
此客户端库支持Flutter使用Chabok推送库。
通过此库,可以在Flutter环境中调用Chabok的功能。


安装

要安装此插件,请参考Flutter文档并根据平台(Android和iOS)进行设置。


发行说明

您可以在此处找到发行说明:发行说明


支持

如有问题,请访问GitHub Issues


入门指南

Android

在您的应用build.gradle文件中添加依赖项:

plugins {
    id 'com.google.gms.google-services'
}

...

dependencies {
    implementation 'io.chabok:chabok-sdk:1.3.2'
}
Firebase Cloud Messaging

Firebase Cloud Messaging (FCM),以前称为Google Cloud Messaging (GCM),是Android平台上的跨平台云解决方案,用于消息传递和通知。

build.gradle文件中包含以下代码以获取FCM API支持:

dependencies {
    implementation 'com.google.firebase:firebase-messaging: 23.0.0'
}
buildscript {
    dependencies {
        classpath "com.google.gms:google-services:4.3.2"
    }
}

初始化

MainApplication文件中初始化Chabok SDK:

注意: 调用Chabok.initialize()是使用Chabok SDK的必要步骤。

Java代码示例:

import io.chabok.Callback;
import io.chabok.Chabok;
import io.flutter.app.FlutterApplication;

public class MainApplication extends FlutterApplication {
    @Override
    public void onCreate() {
        super.onCreate();

        Chabok.setActivity(MainActivity.class);

        Chabok.initialize("APP_ID", "SECRET", new Callback() {
            @Override
            public void onResponse(boolean success, @Nullable String message) {
                if(success) {
                    // 已初始化
                } else {
                    // 未初始化
                }
            }
        });
    }
}

Kotlin代码示例:

import io.chabok.Chabok  
import io.chabok.Callback  
import io.flutter.app.FlutterApplication;
  
class MainApplication : FlutterApplication() {  
  
    override fun onCreate() {  
        super.onCreate()  

        Chabok.setActivity(HomeActivity::class.java)
  
        Chabok.initialize("APP_ID", "SECRET", object : Callback {  
            override fun onResponse(success: Boolean, message: String?) {  
                if (success) {  
                    print("The Chabok SDK has been successfully initialized")  
                } else {  
                    print("$message")  
                }  
            }  
        })  
    }  
}

注意: 应用程序凭据(APP_IDSECRET)可在您的仪表板空间中的应用信息部分找到。

将您的APP_IDSECRET从仪表板放入initialize方法中。


iOS

MainApplication文件中初始化Chabok SDK:

注意: 调用Chabok.initialize()是使用Chabok SDK的必要步骤。

Objective-C代码示例:

#import <ChabokSDK/ChabokSDK-Swift.h>

[Chabok initializeWithAppId:@"APP_ID" secret:@"SECRET" callback:^(BOOL success, NSString* message) {
    if (success) {
      NSLog(@"The Chabok SDK has been successfully initialized");
    } else {
      NSLog(@"%@", message);
    }
}];

Swift代码示例:

import ChabokSDK

Chabok.initialize(appId: "APP_ID", secret: "SECRET") {
    (success,message) in
    if (success) {  
      print("The Chabok SDK has been successfully initialized")  
    } else {  
      print("\(data)") 
    }
}

使用

在您的main.dart文件中:

初始化

在Flutter中初始化Chabok SDK时,在import部分添加以下代码:

import 'package:chabok_flutter/Chabok.dart';
import 'package:chabok_flutter/user/Profile.dart';
import 'package:chabok_flutter/user/Gender.dart';
用户

Chabok的USERNAME是一个唯一标识符,可以为每个用户分配以识别他/她。 例如,一个唯一的ID可以是一个生成的UUID或手机号码等。

理想情况下,您应在用户注册、登录或身份已知的页面上为其分配唯一ID。


登录

初始化Chabok后,使用login方法来识别系统中的用户,以便监控所有行为和属性与用户身份相关联。 我们建议您在OTP页面上使用Chabok的登录功能。

当用户登录时,所有存储的信息都会与已识别的用户关联。

要登录Chabok服务中的用户,请使用login方法:

Chabok.user().login("USERNAME");

带回调的loginUser方法:

Chabok.user().login("USERNAME").then((response) {
    setState(() {
      Map<String, dynamic> responseJson = json.decode(response);
      final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ logged in suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in login $message');
      }
    });
});

示例

在验证用户OTP代码时,我们应该登录到Chabok平台以通过用户ID识别用户:

Chabok.user().login("989100360500");

注销

通过调用以下方法,即使用户从其账户中注销,您仍然可以通过访客ID与用户保持互动。

当用户退出您的应用程序时,请调用Chabok注销方法,以避免将未来的属性、事件和其他数据附加到此用户,直到再次调用login方法为止。

logout方法可用于注销Chabok中的用户:

Chabok.user().logout();

带回调的logout方法:

Chabok.user().logout().then((response) {
    setState(() {
      Map<String, dynamic> responseJson = json.decode(response);
      final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ logged out suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in logout $message');
      }
    });
});
检查用户是否已登录

要检查用户是否已登录Chabok,请使用以下方法:

Chabok.user().isLoggedIn((result) {
      if(result) {
        print("User is loggedIn");
      } else {
        print("User is not loggedIn");
      }
});

提示: 如果您已经在应用程序中实现了Chabok,则可以使用以下方法来检查和登录已登录但未登录Chabok的用户:

Chabok.user().isLoggedIn((result) {
      if(!result) {
        Chabok.loginUser("USER_ID")
      }
});

标签

要在Chabok服务中设置用户标签,请使用setTag方法:

Chabok.user().setTag("TAG");

要设置多个标签,请使用setTags方法:

Chabok.user().setTags(List<String>);

示例

Chabok.user().setTags("VIP");
List<String> tags = ["VIP", "PURCHASED"];
Chabok.user().setTags(tags);

带回调的设置用户标签方法:

Chabok.user().setTag(tag.text.toString()).then((response) {
    setState(() {
      Map<String, dynamic> responseJson = json.decode(response);
      final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ set user tag suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in set user tag $message');
      }
    });
});

要取消用户标签,请使用unsetTag方法:

Chabok.user().unsetTag("TAG");

要取消多个标签,请使用unsetTags方法:

Chabok.user().unsetTags(List<String>);

示例

Chabok.user().unsetTag("VIP");
List<String> tags = ["VIP", "PURCHASED"];
Chabok.user().unsetTags(tags);

带回调的取消用户标签方法:

Chabok.user().unsetTag(tag.text.toString()).then((response) {
    setState(() {
      Map<String, dynamic> responseJson = json.decode(response);
      final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ unset user tag suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in unset user tag $message');
      }
    });
});

属性

您收集的用户属性可以为您提供全面的用户画像,包括他们的身份、来源、行为等。属性可以是喜好、用户偏好等。您可以基于上下文相关性对用户进行分段,并通过这些细粒度的用户数据个性化营销活动。

要在Chabok服务中设置用户属性,请使用setAttribute方法:

Chabok.user().setAttribute("KEY","VALUE");

示例

Chabok.user().setAttribute("City","Karaj");

带回调的设置用户属性方法:

Chabok.user().setAttribute(attributeKey.text.toString(), attributeValue.text.toString()).then((response) {
    setState(() {
      Map<String, dynamic> responseJson = json.decode(response);
      final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ set user attribute suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in set user attribute $message');
      }
    });
});

要取消用户属性,请使用unsetAttribute方法:

Chabok.user().unsetAttribute("KEY");

示例

Chabok.user().unsetAttribute("City");

带回调的取消用户属性方法:

Chabok.user().unsetAttribute(attributeKey.text.toString()).then((response) {
    setState(() {
      Map<String, dynamic> responseJson = json.decode(response);
      final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ unset user attribute suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in unset user attribute $message');
      }
    });
});

用户档案

使用setProfile方法输入用户信息,如名字、姓氏、性别等。

要在Chabok服务中设置用户的档案信息,请使用setProfile方法:

final profile = Profile();
    profile.email = "EMAIL"; // e.g. dev.chabok@gmail.com
    profile.phoneNumber ="PHONE_NUMBER"; // e.g. 989100360500
    profile.firstName = "FIRSTNAME"; // e.g. Hossein
    profile.lastName = "LASTNAME"; // e.g. Shooshtari
    profile.birthDate = "BIRTH_DATE"; // e.g. (timestamp) 3131231232 
    profile.gender = Gender; // e.g. Gender.MALE
    Chabok.user().setProfile(profile);

带回调的设置用户档案信息方法:

final profile = Profile();
    profile.email = "EMAIL"; // e.g. dev.chabok@gmail.com
    profile.phoneNumber ="PHONE_NUMBER"; // e.g. 989100360500
    profile.firstName = "FIRSTNAME"; // e.g. Hossein
    profile.lastName = "LASTNAME"; // e.g. Shooshtari
    profile.birthDate = "BIRTH_DATE"; // e.g. (timestamp) 3131231232 
    profile.gender = Gender; // e.g. Gender.MALE
    Chabok.user().setProfile(profile).then((response) {
      setState(() {
         Map<String, dynamic> responseJson = json.decode(response);
        final String message = responseJson['message'];
        final bool success = responseJson['success'];
        if(success) {
          print('(CHABOK): Flutter ~~~~~~ set user profile suucessfully');
        } else {
          print('(CHABOK): Flutter ~~~~~~ error in set user profile $message');
        }
      });
    });

通知功能

获取通知负载中的数据

addNotificationHandler() {
    print('(CHABOK): Flutter ~~~~~~ Notification handler called ~~~~~~');
    Chabok.addNotificationHandler((data) {
      print('(CHABOK): Flutter ~~~~~~ New notification data received ~~~> $data');
      Map<String, dynamic> responseJson = json.decode(data);
    });
}

发送通知权限状态

要在Android 13设备上接收推送通知,用户必须允许通知权限。在获取权限后调用以下方法:

Chabok.setNotificationPermissionStatus(false);

向SDK发送Chabok意图

为了获取Android 12设备上的推送通知交付报告,请调用以下方法:

注意: 该方法应在onCreateonNewIntent中调用。

Chabok.passIntent(intent);

调试功能

启用/禁用Chabok SDK

Chabok.disableSdk(false);

设置日志级别

Chabok.setLogLevel(LogLevel.VERBOSE);

锁定SDK的日志记录

Chabok.lockLogging(false);

示例代码

以下是完整的示例代码:

// example/lib/main.dart
import 'dart:collection';
import 'dart:convert';
import 'dart:developer';

import 'package:flutter/material.dart';

import 'package:chabok_flutter/Chabok.dart';
import 'package:chabok_flutter/user/Profile.dart';
import 'package:chabok_flutter/user/Gender.dart';
import 'package:flutter/foundation.dart';
import 'dart:developer' as developer;
import 'dart:async';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  final TextEditingController loginKey = TextEditingController();
  final TextEditingController loginValue = TextEditingController();
  final TextEditingController attributeKey = TextEditingController();
  final TextEditingController attributeValue = TextEditingController();
  final TextEditingController eventKey = TextEditingController();
  final TextEditingController eventValue = TextEditingController();
  final TextEditingController tag = TextEditingController();
  final TextEditingController profileName = TextEditingController();
  final TextEditingController profileFamily = TextEditingController();
  final TextEditingController profileEmail= TextEditingController();
  final TextEditingController profileMobile = TextEditingController();

  Color connectionColor = Colors.red;
  String connectionString = "UNKNOWN";
  String logString = "";

  [@override](/user/override)
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    Chabok.user().isLoggedIn().then((isLoggedIn) {
      setState(() {
      //    Map<String, dynamic> responseJson = json.decode(response);
      //  final String message = responseJson['message'];
      // final bool success = responseJson['success'];
      if(isLoggedIn) {
        print('(CHABOK): Flutter ~~~~~~ User is loggedIn!');
      } else {
        print('(CHABOK): Flutter ~~~~~~ User is not loggedIn!');
      }
      });
    });

     Chabok.user().getUsername().then((username) {
      setState(() {
      print('(CHABOK): Flutter ~~~~~~ Username: $username!');
      });
    });

    // Timer(Duration(seconds: 10), () {
    //   Chabok.setNotificationPermissionStatus(true);
    // });
    
    addNotificationHandler();
    super.initState();
    //debugPrint('(CHABOK)');
  }

  [@override](/user/override)
  void deactivate() {
    // print('deactivate() invoked.');
    super.deactivate();
  }

  [@override](/user/override)
  void dispose() {
    // print('dispose() invoked.');
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  [@override](/user/override)
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // print('state = $state');
  }

  //======================

  addNotificationHandler() {
    print('(CHABOK): Flutter ~~~~~~ Notification handler called ~~~~~~');
    Chabok.message().addNotificationHandler((data) {
      print('(CHABOK): Flutter ~~~~~~ New notification data received ~~~> $data');
      Map<String, dynamic> responseJson = json.decode(data);
    });
  }

  login() {
     print('(CHABOK): Flutter ~~~~~~ login called');
     Chabok.user().login(loginKey.text.toString()).then((response) {
      setState(() {
         Map<String, dynamic> responseJson = json.decode(response);
       final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ logged in suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in login $message');
      }
      });
    });
  }

  logout() {
    Chabok.user().logout().then((response) {
      setState(() {
         Map<String, dynamic> responseJson = json.decode(response);
       final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ logged out suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in logout $message');
      }
      });
    });
  }

  setUserTag() {
    Chabok.user().setTag(tag.text.toString()).then((response) {
      setState(() {
         Map<String, dynamic> responseJson = json.decode(response);
       final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ set user tag suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in set user tag $message');
      }
      });
    });
  }

  unsetUserTag() {
    Chabok.user().unsetTag(tag.text.toString()).then((response) {
      setState(() {
         Map<String, dynamic> responseJson = json.decode(response);
       final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ unset user tag suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in unset user tag $message');
      }
      });
    });
  } 

  setUserAttribute() {
    Chabok.user().setAttribute(attributeKey.text.toString(), attributeValue.text.toString()).then((response) {
      setState(() {
         Map<String, dynamic> responseJson = json.decode(response);
       final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ set user attribute suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in set user attribute $message');
      }
      });
    });
  }

  unsetUserAttribute() {
    Chabok.user().unsetAttribute(attributeKey.text.toString()).then((response) {
      setState(() {
         Map<String, dynamic> responseJson = json.decode(response);
       final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ unset user attribute suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in unset user attribute $message');
      }
      });
    });
  }

  setUserProfile() {
    final profile = Profile();
    profile.email = profileEmail.text.toString();
    profile.phoneNumber = profileMobile.text.toString();
    profile.firstName = profileName.text.toString();
    profile.lastName = profileFamily.text.toString();
    profile.birthDate = 76540911;
    profile.gender = Gender.MALE;
    Chabok.user().setProfile(profile).then((response) {
      setState(() {
         Map<String, dynamic> responseJson = json.decode(response);
       final String message = responseJson['message'];
      final bool success = responseJson['success'];
      if(success) {
        print('(CHABOK): Flutter ~~~~~~ set user profile suucessfully');
      } else {
        print('(CHABOK): Flutter ~~~~~~ error in set user profile $message');
      }
      });
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 10.0);
    Color color = Theme.of(context).primaryColor;

    Widget loginSection = Container(
      padding: const EdgeInsets.only(left: 15,right: 15),
      child: Column(
        children: [
          Container(
            margin: const EdgeInsets.only(top: 15),
            child: Row(
                children: [
                  Text(
                      'Login',
                      style: TextStyle(
                          fontFamily: 'Montserrat',
                          fontSize: 15.0,
                          fontWeight: FontWeight.bold
                      )
                  )
                ]
            ),
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  margin: const EdgeInsets.only(top: 15),
                  height: 30,
                  child: Padding(
                    padding: const EdgeInsets.only(right: 15),
                    child: TextField(
                        controller: loginKey,
                        decoration: InputDecoration(
                            hintText: 'key'
                        )
                    ),
                  ),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: Container(
            width: 200,
              padding: const EdgeInsets.all(8),
              child: MaterialButton(
                  color: color,
                  onPressed: login,
                  child: Text("LOGIN",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                          color: Colors.white,
                          fontWeight: FontWeight.bold
                      )
                  )
              )
          ),
              ),
              Expanded(
                flex: 1,
                child: Container(
            width: 200,
              padding: const EdgeInsets.all(8),
              child: MaterialButton(
                  color: color,
                  onPressed: logout,
                  child: Text("LOGOUT",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                          color: Colors.white,
                          fontWeight: FontWeight.bold
                      )
                  )
              )
          ),
              ),
            ],
          ),
          
        ],
      ),
    );

    Widget attribueSection = Container(
      padding: const EdgeInsets.only(left: 15,right: 15),
      child: Column(
        children: [
          Container(
            margin: const EdgeInsets.only(top: 15),
            child: Row(
                children: [
                  Text(
                      'Attribute',
                      style: TextStyle(
                          fontFamily: 'Montserrat',
                          fontSize: 15.0,
                          fontWeight: FontWeight.bold
                      )
                  )
                ]
            ),
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  margin: const EdgeInsets.only(top: 15),
                  height: 30,
                  child: Padding(
                    padding: const EdgeInsets.only(right: 15),
                    child: TextField(
                        controller: attributeKey,
                        decoration: InputDecoration(
                            hintText: 'key'
                        )
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                  margin: const EdgeInsets.only(top: 15),
                  height: 30,
                  child: Padding(
                    padding: const EdgeInsets.only(left: 15),
                    child: TextField(
                        controller: attributeValue,
                        decoration: InputDecoration(
                            hintText: 'value'
                        )
                    ),
                  ),
                ),
              ),
            ],
          ),
           Row(
            children: [
              Expanded(
                flex: 1,
                child: Container(
            width: 200,
              padding: const EdgeInsets.all(8),
              child: MaterialButton(
                  color: color,
                  onPressed: setUserAttribute,
                  child: Text("SET ATTRIBUTE",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                          color: Colors.white,
                          fontWeight: FontWeight.bold
                      )
                  )
              )
          ),
              ),
              Expanded(
                flex: 1,
                child: Container(
            width: 200,
              padding: const EdgeInsets.all(8),
              child: MaterialButton(
                  color: color,
                  onPressed: unsetUserAttribute,
                  child: Text("UNSET ATTRIBUTE",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                          color: Colors.white,
                          fontWeight: FontWeight.bold
                      )
                  )
              )
          ),
              ),
            ],
          ),
        ],
      ),
    );

    
     Widget tagSection = Container(
      padding: const EdgeInsets.only(left: 15,right: 15),
      child: Column(
        children: [
          Container(
            margin: const EdgeInsets.only(top: 15),
            child: Row(
                children: [
                  Text(
                      'Tag',
                      style: TextStyle(
                          fontFamily: 'Montserrat',
                          fontSize: 15.0,
                          fontWeight: FontWeight.bold
                      )
                  )
                ]
            ),
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  margin: const EdgeInsets.only(top: 15),
                  height: 30,
                  child: Padding(
                    padding: const EdgeInsets.only(right: 15),
                    child: TextField(
                        controller: tag,
                        decoration: InputDecoration(
                            hintText: 'tag'
                        )
                    ),
                  ),
                ),
              ),
            ],
          ),
           Row(
            children: [
              Expanded(
                flex: 1,
                child: Container(
            width: 200,
              padding: const EdgeInsets.all(8),
              child: MaterialButton(
                  color: color,
                  onPressed: setUserTag,
                  child: Text("SET TAG",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                          color: Colors.white,
                          fontWeight: FontWeight.bold
                      )
                  )
              )
          ),
              ),
              Expanded(
                flex: 1,
                child: Container(
            width: 200,
              padding: const EdgeInsets.all(8),
              child: MaterialButton(
                  color: color,
                  onPressed: unsetUserTag,
                  child: Text("UNSET TAG",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                          color: Colors.white,
                          fontWeight: FontWeight.bold
                      )
                  )
              )
          ),
              ),
            ],
          ),
        ],
      ),
    );


    Widget profileSection = Container(
      padding: const EdgeInsets.only(left: 15,right: 15),
      child: Column(
        children: [
          Container(
            margin: const EdgeInsets.only(top: 15),
            child: Row(
                children: [
                  Text(
                      'Profile',
                      style: TextStyle(
                          fontFamily: 'Montserrat',
                          fontSize: 15.0,
                          fontWeight: FontWeight.bold
                      )
                  )
                ]
            ),
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  margin: const EdgeInsets.only(top: 15),
                  height: 30,
                  child: Padding(
                    padding: const EdgeInsets.only(right: 15),
                    child: TextField(
                        controller: profileName,
                        decoration: InputDecoration(
                            hintText: 'name'
                        )
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                  margin: const EdgeInsets.only(top: 15),
                  height: 30,
                  child: Padding(
                    padding: const EdgeInsets.only(left: 15),
                    child: TextField(
                        controller: profileFamily,
                        decoration: InputDecoration(
                            hintText: 'family'
                        )
                    ),
                  ),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: Container(
                  margin: const EdgeInsets.only(top: 30),
                  height: 30,
                  child: Padding(
                    padding: const EdgeInsets.only(right: 15),
                    child: TextField(
                        controller: profileEmail,
                        decoration: InputDecoration(
                            hintText: 'email'
                        )
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                  margin: const EdgeInsets.only(top: 30),
                  height: 30,
                  child: Padding(
                    padding: const EdgeInsets.only(left: 15),
                    child: TextField(
                        controller: profileMobile,
                        decoration: InputDecoration(
                            hintText: 'mobile'
                        )
                    ),
                  ),
                ),
              ),
            ],
          ),
          Container(
              width: 200,
              padding: const EdgeInsets.all(8),
              child: MaterialButton(
                  color: color,
                  onPressed: setUserProfile,
                  child: Text("SET PROFILE",
                      textAlign: TextAlign.center,
                      style: style.copyWith(
                          color: Colors.white,
                          fontWeight: FontWeight.bold
                      )
                  )
              )
          )
        ],
      ),
    );

    return MaterialApp(
      title: 'Chabok Demo Flutter',
      home: Scaffold(
        // appBar: AppBar(
        //   title: Text('Chabok Demo'),
        // ),
        body: ListView(
          children: [
            loginSection,
            Divider(),
            attribueSection,
            Divider(),
            tagSection,
            Divider(),
            profileSection,
          ],
        ),
      ),
    );
  }
}

更多关于Flutter消息推送插件chabok_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter消息推送插件chabok_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


chabok_flutter 是一个用于在 Flutter 应用中集成 Chabok 消息推送服务的插件。Chabok 是一个全栈式用户互动平台,提供了消息推送、用户行为分析、实时通知等功能。通过 chabok_flutter 插件,你可以在 Flutter 应用中轻松实现消息推送功能。

以下是使用 chabok_flutter 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 chabok_flutter 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  chabok_flutter: ^1.0.0  # 检查最新版本

然后运行 flutter pub get 来获取依赖。

2. 初始化 Chabok

在你的 Flutter 应用启动时,需要初始化 Chabok 插件。通常,你可以在 main.dart 文件中进行初始化。

import 'package:flutter/material.dart';
import 'package:chabok_flutter/chabok_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化 Chabok
  await Chabok.initialize(
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_API_KEY',
    sandbox: true,  // 设置为 false 以使用生产环境
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

3. 用户注册

在用户登录后,你需要将用户注册到 Chabok 平台,以便能够向该用户发送消息。

Chabok.registerUser(
  userId: 'USER_ID',  // 用户唯一标识
  attributes: {       // 可选:用户属性
    'name': 'John Doe',
    'email': 'john@example.com',
  },
);

4. 接收消息

你可以通过监听 Chabok.onMessage 来接收推送消息。

class MyHomePage extends StatefulWidget {
  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _message = 'No message received';

  [@override](/user/override)
  void initState() {
    super.initState();

    // 监听推送消息
    Chabok.onMessage.listen((Map<String, dynamic> message) {
      setState(() {
        _message = message['body'];
      });
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chabok Flutter Demo'),
      ),
      body: Center(
        child: Text(_message),
      ),
    );
  }
}

5. 发送消息

你可以通过 Chabok 控制台或 API 发送消息到指定的用户或用户组。在 Flutter 应用中,你可以使用 Chabok.sendMessage 方法发送消息。

Chabok.sendMessage(
  userId: 'USER_ID',  // 发送给特定用户
  message: 'Hello, this is a test message!',
);

6. 处理通知点击

当用户点击通知时,你可以通过监听 Chabok.onNotificationClicked 来处理点击事件。

Chabok.onNotificationClicked.listen((Map<String, dynamic> message) {
  // 处理通知点击事件
  print('Notification clicked: ${message['body']}');
});

7. 注销用户

当用户注销时,你需要从 Chabok 平台注销该用户。

Chabok.unregisterUser();

8. 调试

在开发阶段,你可以启用调试日志来查看 Chabok 插件的运行情况。

Chabok.setDebug(true);

9. 处理生命周期

确保在应用的生命周期中正确处理 Chabok 插件的状态。例如,在应用进入后台时,你可能需要暂停 Chabok 的连接。

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  [@override](/user/override)
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  [@override](/user/override)
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  [@override](/user/override)
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      // 应用进入后台
      Chabok.pause();
    } else if (state == AppLifecycleState.resumed) {
      // 应用回到前台
      Chabok.resume();
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!