Skip to main content

form_draft 0.1.0 copy "form_draft: ^0.1.0" to clipboard
form_draft: ^0.1.0 copied to clipboard

Automatically save and restore Flutter form drafts, so users never lose what they typed when the app is backgrounded, killed by the OS, or navigated away by accident.

example/lib/main.dart

import 'dart:io';

// Flutter 3.47 moved the Material widgets to package:material_ui. This package
// also supports older SDKs, where this is still the only import available.
// ignore: deprecated_member_use
import 'package:flutter/material.dart';
import 'package:form_draft/form_draft.dart';
import 'package:form_draft/form_draft_io.dart';

void main() {
  runApp(const ExampleApp());
}

/// A contact form that survives the app being killed.
///
/// The draft is stored in a file inside the temporary directory to keep the
/// example free of plugins. In a real app, use `path_provider`:
///
/// ```dart
/// final directory = await getApplicationSupportDirectory();
/// final store = FileDraftStore(Directory('${directory.path}/drafts'));
/// ```
class ExampleApp extends StatelessWidget {
  /// Creates the example application.
  const ExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'form_draft example',
      theme: ThemeData(colorSchemeSeed: Colors.indigo),
      home: const ContactPage(),
    );
  }
}

/// The page holding the form.
class ContactPage extends StatefulWidget {
  /// Creates the contact page.
  const ContactPage({super.key});

  @override
  State<ContactPage> createState() => _ContactPageState();
}

class _ContactPageState extends State<ContactPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  late final DraftController _controller;
  late final FileDraftStore _store;
  bool _restored = false;

  @override
  void initState() {
    super.initState();
    _store = FileDraftStore(
      Directory('${Directory.systemTemp.path}/form_draft_example'),
    );
    _controller = DraftController(
      id: 'contact',
      store: _store,
      maxAge: const Duration(days: 7),
    );
  }

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

  Future<void> _send() async {
    if (!(_formKey.currentState?.validate() ?? false)) {
      return;
    }
    // The form was submitted: the draft is not needed anymore.
    await _controller.discard();
    _formKey.currentState?.reset();
    if (!mounted) {
      return;
    }
    setState(() => _restored = false);
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('Message sent')));
  }

  Future<void> _discard() async {
    await _controller.discard();
    _formKey.currentState?.reset();
    if (!mounted) {
      return;
    }
    setState(() => _restored = false);
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('Draft discarded')));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Contact us'),
        actions: <Widget>[
          IconButton(
            tooltip: 'Discard draft',
            onPressed: _discard,
            icon: const Icon(Icons.delete_outline),
          ),
        ],
      ),
      body: DraftForm(
        controller: _controller,
        formKey: _formKey,
        onRestored: (DraftSnapshot? snapshot) {
          if (snapshot != null && mounted) {
            setState(() => _restored = true);
          }
        },
        builder: (BuildContext context) => ListView(
          padding: const EdgeInsets.all(16),
          children: <Widget>[
            if (_restored)
              Card(
                color: Theme.of(context).colorScheme.secondaryContainer,
                child: const Padding(
                  padding: EdgeInsets.all(12),
                  child: Row(
                    children: <Widget>[
                      Icon(Icons.restore),
                      SizedBox(width: 12),
                      Expanded(
                        child: Text(
                          'Your last draft was restored. Close the app while '
                          'typing and come back: nothing is lost.',
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            const SizedBox(height: 8),
            DraftTextFormField(
              draftKey: 'name',
              textInputAction: TextInputAction.next,
              decoration: const InputDecoration(
                labelText: 'Name',
                border: OutlineInputBorder(),
              ),
              validator: (String? value) =>
                  (value == null || value.trim().isEmpty) ? 'Required' : null,
            ),
            const SizedBox(height: 12),
            DraftTextFormField(
              draftKey: 'email',
              keyboardType: TextInputType.emailAddress,
              textInputAction: TextInputAction.next,
              decoration: const InputDecoration(
                labelText: 'Email',
                border: OutlineInputBorder(),
              ),
              validator: (String? value) =>
                  (value == null || !value.contains('@')) ? 'Invalid' : null,
            ),
            const SizedBox(height: 12),
            // Passwords and card numbers must never be drafted.
            DraftTextFormField(
              draftKey: 'password',
              draftable: false,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: 'Password (never saved)',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            DraftTextFormField(
              draftKey: 'message',
              maxLines: 5,
              decoration: const InputDecoration(
                labelText: 'Message',
                alignLabelWithHint: true,
                border: OutlineInputBorder(),
              ),
              validator: (String? value) =>
                  (value == null || value.trim().length < 10)
                  ? 'At least 10 characters'
                  : null,
            ),
            const SizedBox(height: 8),
            DraftValueBuilder<bool>(
              draftKey: 'newsletter',
              initialValue: false,
              builder:
                  (
                    BuildContext context,
                    bool value,
                    ValueChanged<bool> onChanged,
                  ) => SwitchListTile(
                    contentPadding: EdgeInsets.zero,
                    title: const Text('Subscribe to the newsletter'),
                    value: value,
                    onChanged: onChanged,
                  ),
            ),
            const SizedBox(height: 16),
            FilledButton(onPressed: _send, child: const Text('Send')),
          ],
        ),
      ),
    );
  }
}
2
likes
160
points
65
downloads

Documentation

API reference

Publisher

verified publisherthodz.com

Weekly Downloads

Automatically save and restore Flutter form drafts, so users never lose what they typed when the app is backgrounded, killed by the OS, or navigated away by accident.

Repository (GitHub)
View/report issues

Topics

#form #draft #autosave #persistence #mobile

License

MIT (license)

Dependencies

flutter

More

Packages that depend on form_draft