Skip to main content

supabase_flutter 3.0.0-dev.19 copy "supabase_flutter: ^3.0.0-dev.19" to clipboard
supabase_flutter: ^3.0.0-dev.19 copied to clipboard

Flutter integration for Supabase. This package makes it simple for developers to build secure and scalable products.

example/lib/main.dart

import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

import 'supabase_schema.g.dart';

const _accentColor = Color(0xFF3ECF8E);
const _borderColor = Color(0xFF9E9E9E);
const _errorColor = Color(0xFFD32F2F);
const _textColor = Color(0xFF1C1C1C);
const _whiteColor = Color(0xFFFFFFFF);

typedef _ShowMessage = void Function(String? message, {bool isError});

Future<void> main() async {
  await Supabase.initialize(
    url: 'SUPABASE_URL',
    publishableKey: 'SUPABASE_PUBLISHABLE_KEY',
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return WidgetsApp(
      title: 'Supabase Flutter Demo',
      color: _accentColor,
      textStyle: const TextStyle(color: _textColor, fontSize: 16),
      home: const MyWidget(),
      pageRouteBuilder: <T>(settings, builder) => PageRouteBuilder<T>(
        settings: settings,
        pageBuilder: (context, animation, secondaryAnimation) =>
            builder(context),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  const MyWidget({super.key});

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  User? _user;
  String? _message;
  var _messageIsError = false;
  StreamSubscription<AuthState>? _authSubscription;

  @override
  void initState() {
    super.initState();
    _user = Supabase.instance.client.auth.currentUser;
    _authSubscription = Supabase.instance.client.auth.onAuthStateChange.listen(
      (data) {
        final user = data.session?.user;
        setState(() {
          if (user?.id != _user?.id) _message = null;
          _user = user;
        });
      },
      onError: (error, stackTrace) {
        // Network errors (e.g. offline) are emitted as stream errors.
        // Handle or log them here; omitting this handler causes an unhandled
        // exception when the device has no connectivity.
      },
    );
  }

  @override
  void dispose() {
    unawaited(_authSubscription?.cancel());
    super.dispose();
  }

  void _showMessage(String? message, {bool isError = false}) {
    if (!mounted) return;
    setState(() {
      _message = message;
      _messageIsError = isError;
    });
  }

  @override
  Widget build(BuildContext context) {
    final message = _message;
    return ColoredBox(
      color: _whiteColor,
      child: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const ColoredBox(
              color: _accentColor,
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Text(
                  'Profile Example',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
              ),
            ),
            Expanded(
              child: _user == null
                  ? _LoginForm(onMessage: _showMessage)
                  : _ProfileForm(onMessage: _showMessage),
            ),
            if (message != null) _Message(message, isError: _messageIsError),
          ],
        ),
      ),
    );
  }
}

class _LoginForm extends StatefulWidget {
  const _LoginForm({required this.onMessage});

  final _ShowMessage onMessage;

  @override
  State<_LoginForm> createState() => _LoginFormState();
}

class _LoginFormState extends State<_LoginForm> {
  bool _loading = false;
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();

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

  Future<void> _signIn() async {
    setState(() {
      _loading = true;
    });
    widget.onMessage(null);
    try {
      await Supabase.instance.client.auth.signInWithPassword(
        email: _emailController.text,
        password: _passwordController.text,
      );
    } catch (_) {
      widget.onMessage('Login failed', isError: true);
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    }
  }

  Future<void> _signUp() async {
    setState(() {
      _loading = true;
    });
    widget.onMessage(null);
    try {
      await Supabase.instance.client.auth.signUp(
        email: _emailController.text,
        password: _passwordController.text,
      );
    } catch (_) {
      widget.onMessage('Signup failed', isError: true);
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return _loading
        ? const Center(child: Text('Loading'))
        : ListView(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
            children: [
              _TextInput(
                label: 'Email',
                keyboardType: TextInputType.emailAddress,
                autofillHints: const [AutofillHints.email],
                controller: _emailController,
              ),
              const SizedBox(height: 16),
              _TextInput(
                label: 'Password',
                obscureText: true,
                autofillHints: const [AutofillHints.password],
                controller: _passwordController,
              ),
              const SizedBox(height: 16),
              _Button(
                label: 'Login',
                onPressed: () => unawaited(_signIn()),
              ),
              const SizedBox(height: 16),
              _Button(
                label: 'Signup',
                onPressed: () => unawaited(_signUp()),
              ),
            ],
          );
  }
}

class _ProfileForm extends StatefulWidget {
  const _ProfileForm({required this.onMessage});

  final _ShowMessage onMessage;

  @override
  State<_ProfileForm> createState() => _ProfileFormState();
}

class _ProfileFormState extends State<_ProfileForm> {
  var _loading = true;
  final _usernameController = TextEditingController();
  final _websiteController = TextEditingController();

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

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

  Future<void> _loadProfile() async {
    try {
      final userId = Supabase.instance.client.auth.currentUser!.id;
      final profile = await Supabase.instance.client
          .table(Profiles.table)
          .select()
          .where(Profiles.id.eq(userId))
          .maybeSingle();
      if (profile != null && mounted) {
        setState(() {
          _usernameController.text = profile.username ?? '';
          _websiteController.text = profile.website ?? '';
        });
      }
    } catch (_) {
      widget.onMessage('Error occurred while getting profile', isError: true);
    }
    if (mounted) {
      setState(() {
        _loading = false;
      });
    }
  }

  Future<void> _signOut() async {
    widget.onMessage(null);
    try {
      await Supabase.instance.client.auth.signOut();
    } on AuthException {
      widget.onMessage(
        'Signed out, but the session was not revoked',
        isError: true,
      );
    }
  }

  Future<void> _saveProfile() async {
    setState(() {
      _loading = true;
    });
    widget.onMessage(null);
    try {
      final userId = Supabase.instance.client.auth.currentUser!.id;
      await Supabase.instance.client
          .table(Profiles.table)
          .upsert(
            ProfilesInsert(
              id: userId,
              username: _usernameController.text,
              website: _websiteController.text,
              updatedAt: DateTime.now(),
            ),
          );
      widget.onMessage('Saved profile');
    } catch (_) {
      widget.onMessage('Error saving profile', isError: true);
    }
    if (mounted) {
      setState(() {
        _loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return _loading
        ? const Center(child: Text('Loading'))
        : ListView(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
            children: [
              _TextInput(label: 'Username', controller: _usernameController),
              const SizedBox(height: 16),
              _TextInput(
                label: 'Website',
                keyboardType: TextInputType.url,
                controller: _websiteController,
              ),
              const SizedBox(height: 16),
              _Button(
                label: 'Save',
                onPressed: () => unawaited(_saveProfile()),
              ),
              const SizedBox(height: 16),
              _Button(
                label: 'Sign Out',
                onPressed: () => unawaited(_signOut()),
              ),
            ],
          );
  }
}

class _TextInput extends StatefulWidget {
  const _TextInput({
    required this.label,
    required this.controller,
    this.keyboardType,
    this.autofillHints,
    this.obscureText = false,
  });

  final String label;
  final TextEditingController controller;
  final TextInputType? keyboardType;
  final Iterable<String>? autofillHints;
  final bool obscureText;

  @override
  State<_TextInput> createState() => _TextInputState();
}

class _TextInputState extends State<_TextInput>
    implements TextSelectionGestureDetectorBuilderDelegate {
  final _focusNode = FocusNode();
  late final _gestureDetectorBuilder = TextSelectionGestureDetectorBuilder(
    delegate: this,
  );

  @override
  final editableTextKey = GlobalKey<EditableTextState>();

  @override
  bool get forcePressEnabled => false;

  @override
  bool get selectionEnabled => true;

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

  @override
  Widget build(BuildContext context) {
    return _gestureDetectorBuilder.buildGestureDetector(
      behavior: HitTestBehavior.translucent,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: 4,
        children: [
          Text(widget.label),
          DecoratedBox(
            decoration: BoxDecoration(
              border: Border.all(color: _borderColor),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: EditableText(
                key: editableTextKey,
                controller: widget.controller,
                focusNode: _focusNode,
                keyboardType: widget.keyboardType,
                autofillHints: widget.autofillHints,
                obscureText: widget.obscureText,
                rendererIgnoresPointer: true,
                style: const TextStyle(color: _textColor, fontSize: 16),
                cursorColor: _accentColor,
                backgroundCursorColor: _borderColor,
                selectionColor: _accentColor.withValues(alpha: 0.4),
                contextMenuBuilder: (context, editableTextState) =>
                    _TextContextMenu(editableTextState: editableTextState),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _TextContextMenu extends StatelessWidget {
  const _TextContextMenu({required this.editableTextState});

  final EditableTextState editableTextState;

  @override
  Widget build(BuildContext context) {
    final anchors = editableTextState.contextMenuAnchors;
    return CustomSingleChildLayout(
      delegate: TextSelectionToolbarLayoutDelegate(
        anchorAbove: anchors.primaryAnchor,
        anchorBelow: anchors.secondaryAnchor ?? anchors.primaryAnchor,
      ),
      child: DecoratedBox(
        decoration: BoxDecoration(
          color: _whiteColor,
          border: Border.all(color: _borderColor),
          borderRadius: BorderRadius.circular(4),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            for (final item in editableTextState.contextMenuButtonItems)
              _TextContextMenuButton(item: item),
          ],
        ),
      ),
    );
  }
}

class _TextContextMenuButton extends StatelessWidget {
  const _TextContextMenuButton({required this.item});

  final ContextMenuButtonItem item;

  String get _label =>
      item.label ??
      switch (item.type) {
        ContextMenuButtonType.cut => 'Cut',
        ContextMenuButtonType.copy => 'Copy',
        ContextMenuButtonType.paste => 'Paste',
        ContextMenuButtonType.selectAll => 'Select all',
        ContextMenuButtonType.delete => 'Delete',
        ContextMenuButtonType.lookUp => 'Look up',
        ContextMenuButtonType.searchWeb => 'Search web',
        ContextMenuButtonType.share => 'Share',
        ContextMenuButtonType.liveTextInput => 'Scan text',
        ContextMenuButtonType.custom => '',
      };

  @override
  Widget build(BuildContext context) {
    return Semantics(
      button: true,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: item.onPressed,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: Text(_label),
        ),
      ),
    );
  }
}

class _Button extends StatefulWidget {
  const _Button({required this.label, required this.onPressed});

  final String label;
  final VoidCallback onPressed;

  @override
  State<_Button> createState() => _ButtonState();
}

class _ButtonState extends State<_Button> {
  var _focused = false;

  void _activate(ActivateIntent intent) => widget.onPressed();

  @override
  Widget build(BuildContext context) {
    return Semantics(
      button: true,
      child: FocusableActionDetector(
        mouseCursor: SystemMouseCursors.click,
        onShowFocusHighlight: (focused) => setState(() => _focused = focused),
        actions: {
          ActivateIntent: CallbackAction<ActivateIntent>(
            onInvoke: _activate,
          ),
        },
        child: GestureDetector(
          onTap: widget.onPressed,
          child: DecoratedBox(
            decoration: BoxDecoration(
              color: _accentColor,
              border: Border.all(
                color: _focused ? _textColor : _accentColor,
                width: 2,
              ),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: Text(widget.label, textAlign: TextAlign.center),
            ),
          ),
        ),
      ),
    );
  }
}

class _Message extends StatelessWidget {
  const _Message(this.message, {required this.isError});

  final String message;
  final bool isError;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Text(
        message,
        style: TextStyle(color: isError ? _errorColor : _textColor),
      ),
    );
  }
}