Skip to main content

mesibo 2.15.1 copy "mesibo: ^2.15.1" to clipboard
mesibo: ^2.15.1 copied to clipboard

mesibo is a real-time communication platform for adding end-to-end encrypted messaging, group chat, voice & video calls, and conferencing to mobile and web apps. It is completely free for development, [...]

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mesibo/mesibo.dart';

import 'dart:developer';
      
/**************************************************************************************************
 This demo application implements real-time messaging, calls, and conferencing capabilities in a 
 Flutter application. It can serve as a guide for integrating these features into your own Flutter 
 projects. Please refer to the tutorial link below for details on getting started, obtaining 
 authentication tokens and other implementation specifics.

 https://docs.mesibo.com/tutorials/get-started/

 You MUST create tokens and initialize them for user1 and user2 in the code below.

 **************************************************************************************************/

/* ============= IMPORTANT NOTE ============
   
   Although the mesibo Flutter SDK includes all essential messaging, call, and conferencing features, 
   it is a limited version compared to the complete native Android and iOS mesibo APIs. 
   The Flutter SDK is actively expanding and will soon have all native mesibo API features. 
   However, if you need any specific native mesibo API not yet in the Flutter SDK, 
   please write to us, and we will prioritize adding that feature.
*/



class DemoUser {
  String token = "";
  String address = "";

  DemoUser(String t, String a) {
    token = t;
    address = a;
  }
}

void main() {
  runApp(FirstMesiboApp());
}

/// Home widget to display video chat option.
class FirstMesiboApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Mesibo Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text("First Mesibo App"),
        ),
        body:  HomeWidget(),

      ),
      debugShowCheckedModeBanner: false,
    );
  }
}

/// Widget to display start video call layout.
class HomeWidget extends StatefulWidget {
  @override
  _HomeWidgetState createState() => _HomeWidgetState();
}

class _HomeWidgetState extends State<HomeWidget> implements MesiboConnectionListener, MesiboMessageListener, MesiboGroupListener, MesiboPhoneContactsListener, MesiboCallIncomingListener, MesiboLocationListener, MesiboProfileSearchListener, MesiboUIMenuListener, MesiboEditProfileListener, MesiboUIHelperListener {
  static Mesibo _mesibo = Mesibo();
  static MesiboUI _mesiboUi = MesiboUI();
  String _mesiboStatus = 'Mesibo status: Not Connected.';
  Text? mStatusText;
  bool authFail = false;
  String mAppId = "";

 /**************************************************************************************************
   Please refer to the tutorial link below for details on obtaining user authentication tokens.

   https://docs.mesibo.com/tutorials/get-started/

   Create two users in the mesibo console, and pass their tokens and addresses when you run the
   app, so that they are never in the source code:

     flutter run --dart-define=USER1_TOKEN=<token> --dart-define=USER1_ADDRESS=<address> \
                 --dart-define=USER2_TOKEN=<token> --dart-define=USER2_ADDRESS=<address>

   Log in as User-1 on one device and as User-2 on another: each sends messages and calls to the
   other user's address.

   A token works only for the App ID it was created with. Create the tokens with the App ID of
   this example, com.mesibo.flutter.example: the same on Android (applicationId in
   android/app/build.gradle) and iOS (Bundle Identifier of the Runner target), so the same tokens
   work on both. If you change it, change it on both.
 **************************************************************************************************/
  DemoUser user1 = DemoUser(const String.fromEnvironment("USER1_TOKEN", defaultValue: "<user-1-token>"),
                            const String.fromEnvironment("USER1_ADDRESS", defaultValue: "<user-1-address>"));
  DemoUser user2 = DemoUser(const String.fromEnvironment("USER2_TOKEN", defaultValue: "<user-2-token>"),
                            const String.fromEnvironment("USER2_ADDRESS", defaultValue: "<user-2-address>"));

  String remoteUser = "";
  bool mOnline = false, mLoginDone = false;
  ElevatedButton? loginButton1, loginButton2;

  @override
  void initState() {
    super.initState();
  }

  @override
  void Mesibo_onConnectionStatus(int status) {
    print('Mesibo_onConnectionStatus: ' + status.toString());

    if(authFail) return;  // to prevent overwriting displayed status
    String statusText = status.toString();
    if(status == Mesibo.MESIBO_STATUS_ONLINE) {
        statusText = "Online";
    } else if(status == Mesibo.MESIBO_STATUS_CONNECTING) {
        statusText = "Connecting";
    } else if(status == Mesibo.MESIBO_STATUS_CONNECTFAILURE) {
        statusText = "Connect Failed";
    } else if(status == Mesibo.MESIBO_STATUS_NONETWORK) {
        statusText = "No Network";        
    } else if(status == Mesibo.MESIBO_STATUS_AUTHFAIL) {
        authFail = true;
        String warning = "The token is invalid. Ensure that you have used appid \"" + mAppId + "\" to generate Mesibo user access token";
        statusText = warning;
        print(warning);
        showAlert("Auth Fail", warning);
    } 

    _mesiboStatus = 'Mesibo status: ' + statusText;
    setState(() {});

    if(1 == status) mOnline = true;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        InfoTitle(),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            loginButton1 = ElevatedButton(
              child: Text("Login as User-1"),
              onPressed: _loginUser1,
            ),
            loginButton2 = ElevatedButton(
              child: Text("Login as User-2"),
              onPressed: _loginUser2,
            ),
          ],
        ),

        Container(
          margin: const EdgeInsets.all(10.0),
          padding: const EdgeInsets.all(10.0),
          decoration: BoxDecoration(
          border: Border.all(color: Colors.grey)
        ),
        child: Text(_mesiboStatus, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
        ), 

        mStatusText = Text(""),

        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            loginButton1 = ElevatedButton(
              child: Text("Send a Message"),
              onPressed: _sendMessage,
            ),
            loginButton2 = ElevatedButton(
              child: Text("Set Profile Info"),
              onPressed: _setProfileInfo,
            ),
          ],
        ),

      Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            ElevatedButton(
              child: Text("Show Messages"),
              onPressed: _showMessages,
            ),
            ElevatedButton(
               child: Text("Show User List"),
                onPressed: _showUserList,
            ),
          ],
        ),

        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            ElevatedButton(
              child: Text("Read Summary"),
              onPressed: _readSummary,
            ),
            ElevatedButton(
              child: Text("Read Messages"),
              onPressed: _readMessages,
            ),
          ],
        ),

        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            ElevatedButton(
              child: Text("Video Call"),
              onPressed: _videoCall,
            ),
            ElevatedButton(
              child: Text("Audio Call"),
              onPressed: _audioCall,
            ),
          ],
        ),

        ElevatedButton(
          child: Text("Group Call"),
          onPressed: _groupCall,
        ),

        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            ElevatedButton(
              child: Text("Sync Phone Contacts"),
              onPressed: _syncPhoneContacts,
            ),
            ElevatedButton(
               child: Text("Get Phone Contact"),
                onPressed: _getPhoneContacts,
            ),
          ],
        ),
        ElevatedButton(
          child: Text("Welcome and Login Screens"),
          onPressed: _showWelcome,
        ),

        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            ElevatedButton(
              child: Text("Sync Location"),
              onPressed: _syncLocation,
            ),
            ElevatedButton(
               child: Text("Get Location"),
                onPressed: _getLocation,
            ),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            ElevatedButton(
              child: Text("Device Location"),
              onPressed: _deviceLocation,
            ),
            ElevatedButton(
               child: Text("Search Location"),
                onPressed: _searchProfiles,
            ),
          ],
        ),

      ],
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  void showAlert(String title, String body) {
    AlertDialog alert = AlertDialog(
      title: Text(title),
      content: Text(body),
    );
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }

  bool isOnline() {
    if(mOnline) return true;
    showAlert("Not Online", "First login with a valid token");
    return false;
  }

  bool hasLoggedIn() {
	  if(mLoginDone) return true;
	  showAlert("Failed", "Login befor calling other APIs");
	  return false;
  }

  void initMesibo(String token) async {
      // optional - only to show alert in AUTHFAIL case (read before starting, so it is set by then)
      mAppId = await _mesibo.getAppIdForAccessToken();

      // initialize mesibo
      _mesibo.setAccessToken(token);
      _mesibo.setListener(this);
      _mesibo.start();

      /* Optional - to get missed call notification MesiboCall_onNotify */
      MesiboCall.setListener(this);

      /**************************************************************************************************
        Optional - To use mesibo Location APIs
         
	https://docs.mesibo.com/api/secure-location/
      **************************************************************************************************/
      _mesibo.getLocationManager().setListener(this);


      /**************************************************************************************************
         override default UI text, colors, etc. Refer to the documentation

	 https://docs.mesibo.com/ui-modules/

	 MesiboUiConfig has the same groups and names on Android and iOS; only the settings you change
	 are applied.
      **************************************************************************************************/

      _mesiboUi.getConfig().then((MesiboUiConfig config) {
        config.userList.showBackButton = true;
        config.userList.title = "My First App";
        _mesiboUi.setConfig(config);
      });

      /**************************************************************************************************
         The code below enables basic UI customization. 
	
         However, you can customize entire user interface by implementing MesiboUIListner for Android and 
         iOS. Refer to 

	https://docs.mesibo.com/ui-modules/customizing/
      **************************************************************************************************/

      // the menu: the default call buttons in chats, and "Edit profile" in the chat list's menu
      // (taps go to MesiboUI_onMenuItem below)
      List<MesiboUIMenuItem> menu = MesiboUI.defaultMenu();
      menu.add(MesiboUIMenuItem(id: "editprofile", title: "Edit profile", icon: MesiboUI.ICON_PERSON,
            screen: MesiboUI.SCREEN_USERLIST, button: false));
      _mesiboUi.setMenu(menu, this);
      
      MesiboCallUiProperties cp = MesiboCallUiProperties();
      cp.showScreenSharing = false;
      _mesiboUi.setCallUiDefaults(cp);
  }

  void _loginUser1() {
    if(null == _mesibo) {
      showAlert("Mesibo NULL", "mesibo null");
      return;
    }
    if(mLoginDone) {
      showAlert("Failed", "You have already initiated login. If the connection status is not 1, check the token and the package name/bundle ID");
      return;
    }
    mLoginDone = true;
    initMesibo(user1.token);
    remoteUser = user2.address;
  }

  void _loginUser2() {
    if(mLoginDone) {
      showAlert("Failed", "You have already initiated login. If the connection status is not 1, check the token and the package name/bundle ID");
      return;
    }
    mLoginDone = true;
    initMesibo(user2.token);
    remoteUser = user1.address;
  }


  void _setProfileInfo() async {
    if(!isOnline()) return;
    MesiboProfile profile = await _mesibo.getSelfProfile() as MesiboProfile;
    profile.reset(); // reset to start fresh
    
    profile.name = "Joe from Flutter";
    profile.setImageUrl("https://images.freeimages.com/images/large-previews/bbb/autumn-in-new-york-5-1360120.jpg");
    profile.setString("status", "setting status from Flutter app");
    
    // You can set more values as required by your app
    //profile.setInt("year", 2024);
    //profile.setBoolean("test", true);
    
    // get all profile values
    //Map<String?, Object?>? values = await profile.getValues();
    //print("profile values: " + values.toString());

    profile.save();
    
  }

  void _sendMessage() async {
    if(!isOnline()) return;
    MesiboProfile profile = await _mesibo.getUserProfile(remoteUser) as MesiboProfile;
    
    MesiboMessage m = profile.newMessage();
    m.message = "Hello from Flutter";
    m.send();
  }

  void _sendPresence() async {
    if(!isOnline()) return;
    MesiboProfile profile = await _mesibo.getUserProfile(remoteUser) as MesiboProfile;

    MesiboPresence m = profile.newPresence();
    m.sendTyping();
  }

  void _showMessages() async {
    if(!isOnline()) return;
    MesiboProfile profile = await _mesibo.getUserProfile(remoteUser) as MesiboProfile;
    
    _mesiboUi.launchMessaging(profile);
  }

  /**************************************************************************************************
     The welcome and login screens of the mesibo UI helper. A real app sends the verification code
     and signs in with its own backend in MesiboUIHelper_onLogin; this demo accepts any number and
     code.
  **************************************************************************************************/
  void _showWelcome() {
    MesiboWelcomeOptions welcome = MesiboWelcomeOptions(
        title: "Messaging & Calls in your apps",
        description: "Add messaging, video and voice calls & conferencing in your apps in no time.",
        buttonText: "Get Started");

    MesiboLoginOptions login = MesiboLoginOptions(
        note: "This demo accepts any verification code.",
        accentColor: 0xff00868b,
        buttonColor: 0xff00868b);

    MesiboUIHelper().launchWelcome(welcome, login, this);
  }

  @override
  Future<bool> MesiboUIHelper_onLogin(String para_phone, String? para_code) async {
    // code null: send a code to the phone; else sign in with the code
    print("MesiboUIHelper_onLogin: phone $para_phone code $para_code");
    return true;
  }

  @override
  void MesiboUIHelper_onLoginComplete() {
    // signed in and the screens have closed: open the next screen here
    showAlert("Signed In", "The login screens have closed.");
  }

  @override
  Future<bool> MesiboUI_onMenuItem(MesiboProfile? profile, String para_id) async {
    if ("editprofile" == para_id) {
      _mesiboUi.launchEditProfile(false, this);
      return true;
    }

    // a built-in item (a call): false lets it do its own action
    return false;
  }

  @override
  void MesiboEditProfile_onSaved(MesiboProfile profile, bool para_newUser) {
    print("MesiboEditProfile_onSaved: " + (profile.name ?? ""));
  }

  void _showUserList() {
    if(!isOnline()) return;
    _mesiboUi.launchUserList();
  }

  void _readSummary() async {
    if(!isOnline()) return;
    MesiboReadSession rs = MesiboReadSession.createReadSummarySession(this);
    rs.read(100);
  }
  
  void _readMessages() async {
    if(!isOnline()) return;
    MesiboProfile profile = await _mesibo.getUserProfile(remoteUser) as MesiboProfile;
    MesiboReadSession rs = profile.createReadSession(this);
    rs.read(100);	
  }

  void _audioCall() async {
    if(!isOnline()) return;
    MesiboProfile profile = await _mesibo.getUserProfile(remoteUser) as MesiboProfile;
    _mesiboUi.call(profile, false);
  }

  void _videoCall() async {
    if(!isOnline()) return;
    MesiboProfile profile = await _mesibo.getUserProfile(remoteUser) as MesiboProfile;
    _mesiboUi.call(profile, true);
  }

  void _groupCall() async {
    if(!isOnline()) return;
    int groupid = 0; // create group first, add memmbers and then execute the following. 

    // disabled by default
    if(0 == groupid) {
      showAlert("No group defined", "Refer to the group management documentation to create a group and add members before using group call function");
      return;
    }

    MesiboProfile profile = await _mesibo.getGroupProfile(groupid) as MesiboProfile;
    _mesiboUi.groupCall(profile, true, true, false, false);
  }

      /**************************************************************************************************
         The code below is to read phone contacts, if required by your app
	
	https://docs.mesibo.com/api/phone-contacts-and-addressbook/
      **************************************************************************************************/

  @override
  void Mesibo_onPhoneContactsChanged() {
  }

  @override
  void Mesibo_onPhoneContactsAdded(List<String?> phones) {
  }
        
  @override
  void Mesibo_onPhoneContactsDeleted(List<String?> phones) {
  }

  void _syncPhoneContacts() async {
    _mesibo.getPhoneContactsManager().setListener(this);
    _mesibo.getPhoneContactsManager().start();
  }

  void _getPhoneContacts() async {
    MesiboPhoneContact contact = (await _mesibo.getPhoneContactsManager().getPhoneNumberInfo("+18005551234", null, true))! as MesiboPhoneContact;

    print("Mesibo Contact: name ${contact.name} phone ${contact.phoneNumber} formatted ${contact.formattedPhoneNumber} country ${contact.country}");
  }

  void _syncLocation() async {
    if(!hasLoggedIn()) return;
    _mesibo.getLocationManager().start(null);
  }
  
  void printLocation(MesiboLocation? loc, String name) {
        if(null == loc)
		print("${name}: null");
       else 
		print("${name}: lat ${loc.latitude} lon ${loc.longitude}");
  }

  void _deviceLocation() async {
    if(!hasLoggedIn()) return;
    MesiboLocation? loc = await _mesibo.getLocationManager().getDeviceLocation() as MesiboLocation?;
    printLocation(loc, "device location");
  }
  
  void _getLocation() async {
    if(!hasLoggedIn()) return;
    MesiboProfile profile = await _mesibo.getUserProfile(remoteUser) as MesiboProfile;
    MesiboLocation? loc = await profile.location().get() as MesiboLocation?;
    printLocation(loc, "profile Location");
  }
  
  void _shareLocation() async {
    if(!hasLoggedIn()) return;
    MesiboProfile profile = await _mesibo.getUserProfile(remoteUser) as MesiboProfile;
    profile.location().share(3600);
  }
  
  void _searchProfiles() async {
    if(!hasLoggedIn()) return;
	MesiboProfileSearch ps = MesiboProfileSearch();
	ps.setDistance(10000);
	ps.setListener(this);
	ps.search();
  }

  void __createGroup() async {
    MesiboGroupSettings settings = MesiboGroupSettings();
    settings.name = "My Group";
  }
  
  @override
  void Mesibo_onMessage(MesiboMessage message) {
    String groupName = "";
    if(null != message.groupProfile)
      groupName = message.groupProfile!.name!;

    print('Mesibo_onMessage: from: (' + message.profile!.name! + ") group: (" + groupName + ") Message: " + message.message!);
    print('Mesibo_onMessage: date: (' + message.getTimestamp().getDate() + ') time: (' + message.getTimestamp().getTime() + ')');

	if(message.isRealtimeMessage()) {
		print("real-time message");
	} else if(message.isDbMessage()) {
		print("db message");
	}
	
	if(message.isIncoming()) {
		print("incoming message");
	} else if(message.isOutgoing()) {
		print("outgoing message");
	}
  }
  
  @override
  void Mesibo_onMessageStatus(MesiboMessage message) {
    print('Mesibo_onMessageStatus: ' + message.status.toString());
  }
  
  @override
  void Mesibo_onMessageUpdate(MesiboMessage message) {
    print('Mesibo_onMessageUpdate: ' + message.message!);
  }

  @override
  void Mesibo_onGroupCreated(MesiboProfile profile) {

  }

  @override
  void Mesibo_onGroupJoined(MesiboProfile profile) {
      print("Mesibo Group Joined: " + profile.name! + " group id: " + profile.groupId.toString());
      MesiboMessage m = profile.newMessage();
      m.message = "Hey, I have joined this group from Flutter";
      m.send();

      MesiboGroupProfile? groupProfile = profile.getGroupProfile();
      if(groupProfile == null) return;
      groupProfile.getMembers(10, false, this);
  }

  @override
  void Mesibo_onGroupLeft(MesiboProfile profile) {
    print("Mesibo Group left: " + profile.name! + " group id: " + profile.groupId.toString());
  }

  @override
  void Mesibo_onGroupMembers(MesiboProfile profile, List<MesiboGroupMember?> members) {
    print("Mesibo Group members: " + profile.name! + " group id: " + profile.groupId.toString());

    for(final m in members) {
        String? name = m?.getProfile()!.getNameOrAddress();
        print("Mesibo group member: " + name!);
    }
  }

  @override
  void Mesibo_onGroupMembersJoined(MesiboProfile profile, List<MesiboGroupMember?> members) {
    print("Mesibo Group members joined: " + profile.name! + " group id: " + profile.groupId.toString());
  }

  @override
  void Mesibo_onGroupMembersRemoved(MesiboProfile profile, List<MesiboGroupMember?> members) {

  }

  @override
  void Mesibo_onGroupSettings(MesiboProfile profile, MesiboGroupSettings? groupSettings, MesiboMemberPermissions? memberPermissions, List<MesiboGroupPin?> groupPins) {

  }

  @override
  void Mesibo_onGroupError(MesiboProfile profile, int error) {

  }

  @override
  void MesiboCall_onNotify(int type, MesiboProfile profile, bool video, MesiboDateTime ts) {
    print("MesiboCall_onNotify: " + profile.name!);
  }
	      
  @override
  void Mesibo_onDeviceLocation(MesiboLocation location) {
	printLocation(location, "Device Location Update");
  }

  @override
  void Mesibo_onLocationReceived(MesiboProfile profile) async {
	print("Mesibo_onLocationReceived");
    	MesiboLocation? loc = await profile.location().get() as MesiboLocation?;
	printLocation(loc, "profile Location updated");
  }

  @override
  void Mesibo_onLocationRequest(MesiboProfile profile, int duration) {
	print("Mesibo_onLocationRequest");
  }

  @override
  void Mesibo_onLocationShared(MesiboProfile profile, int duration) {
	print("Mesibo_onLocationShared");
  }

  @override
  void Mesibo_onLocationError(MesiboProfile profile, int error) {
	print("Mesibo_onLocationError");
  }

  @override
  void Mesibo_onProfileSearchResults(List<MesiboProfile?> profiles, MesiboProfileSearch search) {
	print("Mesibo_onProfileSearchResults: count ${profiles.length}");
	for(final profile in profiles){
		print("Mesibo_onProfileSearchResults: ${profile!.name!}");
	}
  }

  @override
  void Mesibo_onProfileSearchUpdate(List<MesiboProfile?> profiles, MesiboProfileSearch search) {
  }


}

/// Widget to display start video call title.
class InfoTitle extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: Center(
        child: Text(
          "Login as User-1 from one device and as User-2 from another!",
          textAlign: TextAlign.center,
        ),
      ),
    );
  }
}
1
likes
110
points
332
downloads

Documentation

Documentation
API reference

Publisher

unverified uploader

Weekly Downloads

mesibo is a real-time communication platform for adding end-to-end encrypted messaging, group chat, voice & video calls, and conferencing to mobile and web apps. It is completely free for development, education, and non-commercial use.

Homepage
Repository (GitHub)

License

unknown (license)

Dependencies

flutter, meta

More

Packages that depend on mesibo

Packages that implement mesibo