Minimal example

This shows the minimal possible example to integrate Flutter Nakama into your app.

👨‍đŸ’ģ Minimal example

In this example we initialize the Nakama SDK, sign in as a static user and create a match where other user's can join later on.

Initialize SDK

After booting the app, initialize Nakama SDK with required parameters:

import 'package:nakama/nakama.dart';

getNakamaClient(
    host: '127.0.0.1',
    ssl: false,
    serverKey: 'defaultkey',
);

You can optionally provide httpPort and grpcPort if you want to customize them. Default values are same as Nakama's default ports.

Sign In

Sign in with the user's credentials, for example with email & password:

Tip: there is no difference between sign in and sign up at Nakama. You can find out via session.created if the account has been created or it is a recurring sign in.

getNakamaClient().authenticateEmail(
    email: 'foo@bar.de',
    password: 'password',
).then((session) => _session = session);

You receive an instance of Session which contains userId and accessToken among others. You are now logged in.

Initialize / create WebSocket connection

All realtime communication runs though a WebSocket connection. You need to initialize this once after authentication. Then you establish a connection until the user closed the app:

NakamaWebsocketClient.init(
    host: '127.0.0.1',
    ssl: false,
    token: _session.token,
);

Don't forget to close after disposing the app widget:

NakamaWebsocketClient.instance.close();

Create & join a match

The simplest thing is to create a match and join with another's account.

final match = await NakamaWebsocketClient.instance.createMatch();

print('Join my match: ${match.matchId}');

On another instance:

// Get this e.g. via Sharing link or QR Code.
const matchId = '5ef6f886-6afe-49f8-99a0-a53312cd7ac3';

// Join the match with current logged in user.
final joinedMatch = NakamaWebsocketClient.instance.joinMatch(matchId);

Match / Realtime Data

flutter_nakama provides a handy way to listen to realtime events sent from the Nakama server. For example you can listen on match data:

listener = NakamaWebsocketClient.instance.onMatchData.listen((e) {
    print('received match data: ${e.data} from ${e.presence.username}');
});

// Remember closing in dispose() method:
listener.cancel();

You can send match data from your client like so:

NakamaWebsocketClient.instance.sendMatchData(
    matchId: match.matchId,
    opCode: Int64(0),
    data: 'hello world'.codeUnits,
);

Please refer to the Realtime Multiplayer docs on more detailed information on how the realtime data works and which fields are available to use.

You are absolutely free on what and how sending match data. You are free to use JSON or protobuf while the latter might result in very good performance. But you can also just send free text.

Last updated