setup static method

void setup({
  1. required BuildContext context,
  2. String offlineMessage = 'No internet connection',
  3. String onlineMessage = 'Back online',
  4. String? slowMessage,
  5. Duration duration = const Duration(seconds: 3),
})

Wire up automatic snackbars.

  • context: Must be valid throughout the app session.
  • offlineMessage: Shown when connection is lost.
  • onlineMessage: Shown when connection is restored.
  • slowMessage: Shown when connection is slow (optional).

Implementation

static void setup({
  required BuildContext context,
  String offlineMessage = 'No internet connection',
  String onlineMessage = 'Back online',
  String? slowMessage,
  Duration duration = const Duration(seconds: 3),
}) {
  void showSnack(String message, Color color, IconData icon) {
    final messenger = ScaffoldMessenger.maybeOf(context);
    if (messenger == null) return;
    messenger
      ..hideCurrentSnackBar()
      ..showSnackBar(
        SnackBar(
          content: Row(
            children: [
              Icon(icon, color: Colors.white, size: 18),
              const SizedBox(width: 10),
              Expanded(
                child: Text(
                  message,
                  style: const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
          backgroundColor: color,
          duration: duration,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
      );
  }

  _lostHandler = (_) {
    showSnack(offlineMessage, Colors.red.shade700, Icons.wifi_off);
  };

  _restoredHandler = (result) {
    final msg = result.isSlowConnection
        ? (slowMessage ?? '$onlineMessage (slow)')
        : onlineMessage;
    showSnack(msg, Colors.green.shade700, Icons.wifi);
  };

  SmartConnectivityMonitor.instance
      .addConnectionLostListener(_lostHandler!);
  SmartConnectivityMonitor.instance
      .addConnectionRestoredListener(_restoredHandler!);
}