Skip to main content

beeappie_flutter 1.0.0 copy "beeappie_flutter: ^1.0.0" to clipboard
beeappie_flutter: ^1.0.0 copied to clipboard

Users, analytics, crash reports, leaderboards, polls, announcements, feedback, support chat and push for Flutter apps, without a backend.

example/lib/main.dart

import 'dart:async';

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

import 'features/account_page.dart';
import 'features/analytics_page.dart';
import 'features/leaderboards_page.dart';
import 'features/polls_page.dart';
import 'features/privacy_page.dart';
import 'features/promos_page.dart';
import 'features/remote_config_page.dart';
import 'features/remote_content_page.dart';
import 'features/self_test_page.dart';
import 'features/support_page.dart';
import 'features/surveys_page.dart';
import 'features/user_data_page.dart';
import 'local_mode.dart';
import 'sample_setup.dart';
import 'sample_ui.dart';

/// `flutter run --dart-define=SELF_TEST=true` runs every action at launch; `--dart-define=SCREEN=support` opens a screen;
/// `--dart-define=FEATURE=Account` opens a feature's page; `--dart-define=CRASH=dart|native` crashes once started (run it again
/// to send the report).
const selfTest = bool.fromEnvironment('SELF_TEST');
const crash = String.fromEnvironment('CRASH');
const startScreen = String.fromEnvironment('SCREEN');
const startFeature = String.fromEnvironment('FEATURE');


Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Your app's test key: built in (--dart-define=APP_KEY=โ€ฆ), or pasted when the sample first opens (KeyPage).
  final appKey = await SampleKey.appKey();
  if (appKey != null) startBeeAppie(appKey);
  runApp(SampleApp(started: appKey != null));
}

void startBeeAppie(String appKey) {
  final api = localApiUrl(); // null: the SDK's own API, production
  SampleKey.use(appKey);
  BeeAppie.start(appKey, options: api == null ? const BeeAppieOptions() : BeeAppieOptions(baseUrl: api));
  BeeAppie.onPushOpened = (push) => log('Push opened: ${push.data}');
}

/// Every feature, by group: the same groups, names and order in every BeeAppie sample. Each has its page in features/.
final features = <Feature>[
  Feature('Users', '๐Ÿ‘ค', 'Account', 'Sign in, link accounts, user properties',
      'Users start anonymous on each device. Sign in with the same player name on another device: both share scores, chats and votes.',
      'features/account_page.dart', accountPage),
  Feature('Users', '๐Ÿ”’', 'Privacy', 'Consent, download or delete my data',
      'Nothing is collected until the user allows it. The profile screen lets them change their mind.', 'features/privacy_page.dart', privacyPage),
  Feature('Users', '๐Ÿ’พ', 'User data', 'Private settings and saves, synced',
      'Private JSON per user, kept on the device and synced, e.g. settings or saved games. Needs a signed-in user and the app\'s "User data" switch.',
      'features/user_data_page.dart', userDataPage),
  Feature('Measure', '๐Ÿ“ˆ', 'Analytics and errors', 'Events, handled errors, crashes',
      'Events are sent together, every 30 seconds or when the app goes to the background. Screens and steps form the trail shown with each error.',
      'features/analytics_page.dart', analyticsPage),
  Feature('Measure', '๐ŸŽ›๏ธ', 'Remote config and entitlements', 'Values, flags and unlocks from the dashboard',
      'Values and flags change from the dashboard without a new release. Entitlements unlock paid features: store purchases, or grants made in the dashboard.',
      'features/remote_config_page.dart', remoteConfigPage),
  Feature('Measure', '๐Ÿ“ฐ', 'Remote content', 'Lists your team edits in the dashboard',
      'Lists your team writes in the dashboard (Remote content) and the app downloads when it asks: everything the first time, then only what changed.',
      'features/remote_content_page.dart', remoteContentPage),
  Feature('Engage', '๐Ÿ†', 'Leaderboards and achievements', 'Scores, rankings, unlocks',
      'Scores come from your app\'s code: this submits a random score to "high-score", unlocks "First score" and moves "Five games" along (the dashboard\'s "Add the sample\'s content to Test" creates them).',
      'features/leaderboards_page.dart', leaderboardsPage),
  Feature('Engage', '๐Ÿ—ณ๏ธ', 'Polls and announcements', 'Votes and news from your team',
      'Ready-made screens for what your team posts in the dashboard: polls the users vote in, and news and announcements.',
      'features/polls_page.dart', pollsPage),
  Feature('Engage', 'โญ', 'Feature surveys', 'One question, inline or over the screen',
      'One question about a feature, set up in the dashboard (Surveys) and shown by key: inline here, or as a card over the screen. Each install is asked once (these two again a day later); a low answer with a comment arrives under Feedback.',
      'features/surveys_page.dart', surveysPage),
  Feature('Engage', '๐Ÿ“ฃ', 'Promos', 'Your other apps: card, fullscreen, banner',
      'Your company\'s other apps, once their promo is approved in the dashboard (App โ€บ Promos). The card takes no space when there is nothing to show; a fullscreen shows at most every few minutes, never on the first launch.',
      'features/promos_page.dart', promosPage),
  Feature('Support', '๐Ÿ’ฌ', 'Support and feedback', 'Chat with your team, feedback',
      'Ready-made support chat and feedback, or the client API under them: start a conversation with a message, rename it, close it.',
      'features/support_page.dart', supportPage),
  Feature('Tools', '๐Ÿงช', 'Self test', 'Try every feature at once, check the connection',
      'Every feature without a screen, in turn: the results say which worked. Or just check that the app reaches BeeAppie.',
      'features/self_test_page.dart', selfTestPage),
  Feature('Tools', '๐Ÿ“œ', 'Activity', 'Everything the sample did this session',
      'Every result of this session, newest first, whichever page it came from.', null, activityPage),
];

/// Every result of this session, whichever page it came from.
List<Widget> activityPage(FeatureContext page) => [
      ValueListenableBuilder(
        valueListenable: lines,
        builder: (_, entries, _) => Text(entries.isEmpty ? 'Nothing yet: what the feature pages do shows up here.' : entries.join('\n'),
            style: const TextStyle(fontFamily: 'monospace', fontSize: 12, color: ink)),
      ),
    ];

class SampleApp extends StatefulWidget {
  const SampleApp({required this.started, super.key});

  /// False until the developer pastes their app's test key.
  final bool started;

  @override
  State<SampleApp> createState() => _SampleAppState();
}

class _SampleAppState extends State<SampleApp> {
  late bool _started = widget.started;

  @override
  Widget build(BuildContext context) => MaterialApp(
        title: 'BA sample Flutter',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: honey, primary: honey, onPrimary: ink, surface: cream),
          scaffoldBackgroundColor: cream,
        ),
        home: _started
            ? const HomePage()
            : KeyPage(connected: (key) {
                startBeeAppie(key);
                setState(() => _started = true);
              }),
      );
}

/// The home page: who the user is, then every feature by group.
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
    BeeAppie.onUserChanged = (_) => refreshStatus();
    BeeAppie.onSuspended = (_) => refreshStatus();
    // New values arrive at start, when the user changes and when the app returns to the foreground.
    BeeAppie.onConfigChanged = (values) => config.value = values;
    unawaited(_start());
  }

  Future<void> _start() async {
    // The screen goes into the trail sent with errors and crashes.
    BeeAppie.screen('Home');
    await BeeAppie.ensureStarted();
    config.value = await BeeAppie.config();
    await refreshStatus();
    if (selfTest) await runSelfTest(log);
    if (crash.isNotEmpty) {
      BeeAppie.addBreadcrumb('About to crash on purpose');
      await Future<void>.delayed(const Duration(milliseconds: 500));
      crashApp(crash);
    }
    if (startScreen.isNotEmpty) await BeeAppie.openScreen(BeeAppieScreen.values.byName(startScreen));
    if (startFeature.isNotEmpty && mounted) _open(features.firstWhere((f) => f.title.toLowerCase().startsWith(startFeature.toLowerCase())));
  }

  void _open(Feature feature) => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => FeaturePage(feature)));

  @override
  Widget build(BuildContext context) => Scaffold(
        body: SafeArea(
          bottom: false,
          child: ListView(
            padding: const EdgeInsets.all(16),
            children: [
              _header(),
              _statusCard(),
              for (final group in {for (final feature in features) feature.group}) ...[
                Padding(
                  padding: const EdgeInsets.fromLTRB(4, 8, 0, 8),
                  child: Text(group.toUpperCase(), style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: muted)),
                ),
                SampleCard(padding: EdgeInsets.zero, spacing: 0, [
                  for (final (index, feature) in features.where((f) => f.group == group).indexed) ...[
                    if (index > 0) Container(height: 1, margin: const EdgeInsets.only(left: 60), color: cardBorder),
                    _row(feature),
                  ],
                ]),
              ],
            ],
          ),
        ),
        // A banner at the bottom, as where an ad banner would go.
        bottomNavigationBar: const SafeArea(child: BeeAppiePromoBanner()),
      );

  Widget _header() => Padding(
        padding: const EdgeInsets.fromLTRB(4, 8, 0, 16),
        child: Row(children: [
          const SizedBox(width: 40, height: 40, child: CustomPaint(painter: Logo())),
          const SizedBox(width: 12),
          Column(crossAxisAlignment: CrossAxisAlignment.start, children: const [
            Text('BeeAppie', style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: ink)),
            Text('Flutter sample', style: TextStyle(fontSize: 13, color: muted)),
          ]),
        ]),
      );

  Widget _statusCard() => ListenableBuilder(
        listenable: Listenable.merge([status, config]),
        builder: (_, _) => SampleCard([
          // Remote config: values the dashboard changes without a new release.
          if (config.value != null)
            Text(config.value!.getString('welcome_message', fallback: 'Welcome!') ?? '',
                style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: ink)),
          Text(status.value, style: const TextStyle(fontSize: 13, color: muted)),
          if (_appStatus() case final message?) banner(message, const Color(0xFFFFF4D6), const Color(0xFF5C3D00)),
          // Which app key the sample uses, in case you don't remember; a pasted one can be swapped.
          ValueListenableBuilder(
            valueListenable: SampleKey.inUse,
            builder: (_, keyInUse, _) => Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text(keyInUse ?? '', style: const TextStyle(fontSize: 12, color: muted)),
              if (SampleKey.canChange)
                Padding(
                  padding: const EdgeInsets.only(top: 8),
                  child: SampleButton(SampleKey.change, Kind.plain, () async {
                    await SampleKey.forget();
                    SampleKey.inUse.value = SampleKey.forgotten;
                  }),
                ),
            ]),
          ),
        ]),
      );

  /// The app's status, set in the dashboard (App status).
  String? _appStatus() {
    final appStatus = config.value?.status;
    if (appStatus == null) return null;
    if (appStatus.maintenanceMessage?.isNotEmpty == true) return 'Maintenance: ${appStatus.maintenanceMessage}';
    if (appStatus.updateRequired) return 'Please update to version ${appStatus.minimumVersion} to keep using the app.';
    if (appStatus.updateAvailable) return 'Version ${appStatus.latestVersion} is available.';
    return null;
  }

  Widget _row(Feature feature) => InkWell(
        onTap: () => _open(feature),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
          child: Row(children: [
            Container(
              width: 36,
              height: 36,
              alignment: Alignment.center,
              decoration: BoxDecoration(color: sand, borderRadius: BorderRadius.circular(8)),
              child: Text(feature.icon, style: const TextStyle(fontSize: 18)),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                Text(feature.title, style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: ink)),
                Text(feature.line, style: const TextStyle(fontSize: 12, color: muted)),
              ]),
            ),
            const Text('โ€บ', style: TextStyle(fontSize: 22, color: muted)),
          ]),
        ),
      );
}
0
likes
150
points
--
downloads

Documentation

Documentation
API reference

Publisher

verified publisherbeeappie.com

Users, analytics, crash reports, leaderboards, polls, announcements, feedback, support chat and push for Flutter apps, without a backend.

Homepage

Topics

#analytics #crash-reporting #leaderboards #push-notifications #chat

License

unknown (license)

Dependencies

flutter

More

Packages that depend on beeappie_flutter

Packages that implement beeappie_flutter