Swipe to Log In Button in Flutter (No Package)

Build a swipe to log in button in Flutter from scratch: drag the knob, spring back under 80%, show a check on success. Step by step, with the full code from my crypto wallet login UI.

By Yaqoob Developer · · 10 min read

  • #Flutter
  • #Animation
  • #GestureDetector
  • #Login UI
  • #Custom Widget

I had seen "swipe to confirm" buttons in different apps, and I wanted to see if I could build one in Flutter myself. Apps use them for actions where one accidental tap shouldn't count, like confirming a payment. I built mine for the login screen of my Crypto Wallet Login UI.

There are packages for this on pub.dev, but I wanted to build it from scratch to learn how it works. I understand things much better that way, and it turned out to be a small widget: about 110 lines, with no packages except google_fonts for the label.

When I posted the result as a YouTube Short, people asked in the comments how I built it in Flutter and how the code works. This post is my answer, step by step, using the exact code from the project.

Try it first: open the live preview and drag the white knob, or watch the YouTube Short. The full project is on GitHub.

What we are building

An orange pill-shaped button with a white round knob on the left and a label like Swipe to Log In:

  • You drag the knob to the right with your finger.
  • If you let go before 80% of the way, the knob springs back.
  • If you let go after 80%, it finishes the swipe on its own and runs the login.
  • If login fails (for example the email is invalid), the knob springs back.
  • If login succeeds, the arrow turns into a ✓ for a moment, then the button resets.
  • The label fades out as the knob moves over it.

The idea in one minute

The whole button is built around one number between 0 and 1: how far the knob has moved.

  • 0 means the knob is at the start (left).
  • 1 means it reached the end (right).

That number lives in an AnimationController. While you drag, we change the number ourselves. When you let go, we animate it to 0 or 1. Everything on screen, the knob position and the label opacity, is calculated from that one number.

This was the part I struggled with at first: moving the knob with the finger and then bringing it back to its original position smoothly. Once the position is a single value in an AnimationController, both problems become one line each: set the value while dragging, and call reverse() to bring it back.

Step 1: The widget and its sizes

The button takes a label and a callback. The callback returns true if the action worked and false if it didn't, so the button knows whether to show the ✓ or spring back.

class SwipeButton extends StatefulWidget {
  const SwipeButton({super.key, required this.label, required this.onSwiped});

  final String label;
  final bool Function() onSwiped;

  @override
  State<SwipeButton> createState() => _SwipeButtonState();
}

In the state, three constants define the shape: the button height, the padding around the knob, and the knob size, which is the height minus the padding on both sides.

class _SwipeButtonState extends State<SwipeButton>
    with SingleTickerProviderStateMixin {
  static const _height = 66.0;
  static const _pad = 5.0;
  static const _knob = _height - _pad * 2;

Step 2: Store the position in an AnimationController

  late final _progress = AnimationController(
    vsync: this,
    duration: const Duration(milliseconds: 250),
  );
  bool _done = false;

  @override
  void dispose() {
    _progress.dispose();
    super.dispose();
  }
  • _progress.value is our number from 0 to 1. A controller's value starts at 0, which is exactly where the knob should start.
  • The 250 ms duration is how long the knob takes to slide back or finish the swipe.
  • _done is true while the ✓ is showing, so the user can't drag during that moment.
  • Don't forget dispose(). I have forgotten to dispose an animation controller before, and it is an easy mistake to miss.

Step 3: The pill and the knob

The button is a Container with a fully rounded border. Inside it, a Stack holds the label and the knob, and an AnimatedBuilder rebuilds them every time _progress changes.

  @override
  Widget build(BuildContext context) {
    return Container(
      height: _height,
      padding: const EdgeInsets.all(_pad),
      decoration: BoxDecoration(
        color: WalletColors.orange,
        borderRadius: BorderRadius.circular(_height / 2),
      ),
      child: AnimatedBuilder(
        animation: _progress,
        builder: (context, _) => Stack(
          alignment: Alignment.center,
          children: [
            // label (step 6) and knob (step 4) go here
          ],
        ),
      ),
    );
  }

WalletColors.orange is Color(0xFFC8693F) in my project. Use any color you like.

Step 4: Move the knob with your finger

This is the trick that keeps the code short. The knob is placed with Align, and Alignment x runs from -1 (left edge) to 1 (right edge). Our progress runs from 0 to 1, so progress * 2 - 1 converts one into the other:

  • progress 0 → alignment -1 → knob on the left
  • progress 0.5 → alignment 0 → knob in the middle
  • progress 1 → alignment 1 → knob on the right
            Align(
              alignment: Alignment(_progress.value * 2 - 1, 0),
              child: GestureDetector(
                onHorizontalDragUpdate: _done
                    ? null
                    : (d) => _progress.value += d.delta.dx / _travel,
                onHorizontalDragEnd: _done ? null : (_) => _release(),
                child: Container(
                  width: _knob,
                  height: _knob,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    _done ? Icons.check_rounded : Icons.arrow_forward,
                    color: WalletColors.orange,
                  ),
                ),
              ),
            ),

While dragging, d.delta.dx is how many pixels the finger moved since the last update. Dividing it by the distance the knob can travel turns pixels into progress:

  /// How far the knob can move, in pixels.
  double get _travel => context.size!.width - _knob - _pad * 2;

That is the button's width minus the knob and the padding on both sides.

You might expect the knob to slide off the edge if you keep dragging. It doesn't, because an AnimationController clamps its value between 0 and 1 for you. Dragging past the end simply keeps the knob at the end.

The code uses onHorizontalDragUpdate rather than onPanUpdate. A horizontal drag only reacts to sideways movement, so it doesn't fight with a page that scrolls vertically.

Step 5: Let go, the 80% rule

When the finger lifts, _release() decides what happens:

  Future<void> _release() async {
    if (_progress.value < 0.8) {
      await _progress.reverse();
      return;
    }
    await _progress.forward();
    if (!mounted) return;
    if (!widget.onSwiped()) {
      await _progress.reverse();
      return;
    }
    setState(() => _done = true);
    await Future<void>.delayed(const Duration(milliseconds: 1200));
    if (!mounted) return;
    setState(() => _done = false);
    await _progress.reverse();
  }

Step by step:

  1. Less than 80%: reverse() animates the knob back to the start. That is the spring-back.
  2. 80% or more: forward() finishes the swipe to the end.
  3. Then it calls onSwiped(). If that returns false, the knob goes back so the user can try again.
  4. If it returns true, _done shows the ✓ for 1.2 seconds, then the button resets.

Why 80% and not 100%? So the user doesn't have to drag all the way to the very edge. Hitting the last pixel exactly is annoying on a phone, and 80% still makes it clear the swipe was on purpose.

The if (!mounted) return; checks matter because of the awaits: if the user leaves the screen during the animation or the 1.2 second pause, calling setState on a disposed widget would throw an error.

Step 6: Fade the label

The label sits in the same Stack, under the knob. Its opacity is 1 - progress, so it is fully visible at the start and disappears as the knob reaches the end:

            Opacity(
              opacity: 1 - _progress.value,
              child: Padding(
                padding: const EdgeInsets.only(left: _knob),
                child: Text(
                  widget.label,
                  style: GoogleFonts.plusJakartaSans(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
              ),
            ),

The left padding of one knob width keeps the text centered in the free space next to the knob, instead of under it.

The complete SwipeButton

Here is the whole widget, exactly as it is in the project. It needs google_fonts in your pubspec.yaml for the label font, or you can replace GoogleFonts.plusJakartaSans(...) with a normal TextStyle.

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

import '../../theme/wallet_colors.dart';

/// Orange pill with a white knob you drag to the end, like
/// "Swipe to Withdraw". [onSwiped] returns whether the action
/// succeeded; on failure the knob springs back.
class SwipeButton extends StatefulWidget {
  const SwipeButton({super.key, required this.label, required this.onSwiped});

  final String label;
  final bool Function() onSwiped;

  @override
  State<SwipeButton> createState() => _SwipeButtonState();
}

class _SwipeButtonState extends State<SwipeButton>
    with SingleTickerProviderStateMixin {
  static const _height = 66.0;
  static const _pad = 5.0;
  static const _knob = _height - _pad * 2;

  late final _progress = AnimationController(
    vsync: this,
    duration: const Duration(milliseconds: 250),
  );
  bool _done = false;

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

  Future<void> _release() async {
    if (_progress.value < 0.8) {
      await _progress.reverse();
      return;
    }
    await _progress.forward();
    if (!mounted) return;
    if (!widget.onSwiped()) {
      await _progress.reverse();
      return;
    }
    setState(() => _done = true);
    await Future<void>.delayed(const Duration(milliseconds: 1200));
    if (!mounted) return;
    setState(() => _done = false);
    await _progress.reverse();
  }

  /// How far the knob can move, in pixels.
  double get _travel => context.size!.width - _knob - _pad * 2;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: _height,
      padding: const EdgeInsets.all(_pad),
      decoration: BoxDecoration(
        color: WalletColors.orange,
        borderRadius: BorderRadius.circular(_height / 2),
      ),
      child: AnimatedBuilder(
        animation: _progress,
        builder: (context, _) => Stack(
          alignment: Alignment.center,
          children: [
            Opacity(
              opacity: 1 - _progress.value,
              child: Padding(
                padding: const EdgeInsets.only(left: _knob),
                child: Text(
                  widget.label,
                  style: GoogleFonts.plusJakartaSans(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
            Align(
              alignment: Alignment(_progress.value * 2 - 1, 0),
              child: GestureDetector(
                key: const ValueKey('swipe-knob'),
                onHorizontalDragUpdate: _done
                    ? null
                    : (d) => _progress.value += d.delta.dx / _travel,
                onHorizontalDragEnd: _done ? null : (_) => _release(),
                child: Container(
                  width: _knob,
                  height: _knob,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    _done ? Icons.check_rounded : Icons.arrow_forward,
                    color: WalletColors.orange,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Using it on a login screen

On my login screen the button sits at the bottom of the form. The label changes with the selected tab, and onSwiped runs the form validation:

SwipeButton(
  key: ValueKey(_tab),
  label: _isSignUp ? 'Swipe to Sign Up' : 'Swipe to Log In',
  onSwiped: _submit,
),
bool _submit() {
  FocusScope.of(context).unfocus();
  if (!_formKey.currentState!.validate()) return false;
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      content: Text(
        _isSignUp
            ? 'Account created for ${_emailController.text}'
            : 'Logged in as ${_emailController.text}',
      ),
    ),
  );
  return true;
}

Two details worth copying:

  • _submit returns false when validation fails. The form shows its error messages and the knob springs back, so the user fixes the email or password and swipes again. In a real app, this is where you would call your auth code.
  • key: ValueKey(_tab) gives the button a new key when the user switches between Log In and Sign Up. Flutter then creates a fresh button, so a half-finished swipe never carries over to the other tab.

If you only want to try the button, this is enough:

SwipeButton(
  label: 'Swipe to Log In',
  onSwiped: () {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Logged in!')),
    );
    return true; // return false to make the knob spring back
  },
),

Common mistakes

  • Forgetting dispose() on the controller. It keeps ticking after the screen is gone. Always dispose it.
  • Calling setState after an await without checking mounted. The user can leave the screen during the animation. Check mounted after every await that is followed by setState.
  • Using onPanUpdate. It also reacts to vertical movement and can fight with scrolling. onHorizontalDragUpdate only tracks sideways drags.
  • Measuring the travel distance in build. context.size is only available after layout. In this widget it is read during a drag, when the button is already on screen, so it is safe.

Package or your own widget?

If you just need a swipe button quickly, packages like slide_to_confirm or custom_swipe_to_confirm on pub.dev work fine. I built my own because I wanted to learn how it works. A nice side effect is that the widget is small, so changing the height, colors, threshold or animation is just a matter of editing a few constants.

Summary

  • Keep the knob position as one value from 0 to 1 in an AnimationController.
  • Turn it into a position with Alignment(progress * 2 - 1, 0).
  • On drag, add delta.dx / travel to the value; the controller keeps it between 0 and 1.
  • On release, forward() above 80%, reverse() below it or when the action fails.
  • Fade the label with opacity: 1 - progress.

You can see the button in action in the live preview, get the full login screen from the Crypto Wallet Login UI project, and if you are new to forms, read my guide on Flutter form validation next.

Keep reading

More articles