action.action_overridable.0.dart 2.58 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
/// Flutter code sample for [Action.Action.overridable].
6 7 8 9 10 11 12 13

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

void main() {
  runApp(
    const MaterialApp(
      home: Scaffold(
14
        body: Center(child: VerificationCodeGenerator()),
15 16 17 18 19
      ),
    ),
  );
}

20 21 22 23
const CopyTextIntent copyTextIntent = CopyTextIntent._();
class CopyTextIntent extends Intent {
  const CopyTextIntent._();
}
24

25 26
class CopyableText extends StatelessWidget {
  const CopyableText({ super.key, required this.text });
27

28
  final String text;
29

30
  void _copy(CopyTextIntent intent) => Clipboard.setData(ClipboardData(text: text));
31 32 33

  @override
  Widget build(BuildContext context) {
34 35 36 37 38
    final Action<CopyTextIntent> defaultCopyAction = CallbackAction<CopyTextIntent>(onInvoke: _copy);
    return Shortcuts(
      shortcuts: const <ShortcutActivator, Intent> { SingleActivator(LogicalKeyboardKey.keyC, control: true) : copyTextIntent },
      child: Actions(
        actions: <Type, Action<Intent>> {
39 40
          // The Action is made overridable so the VerificationCodeGenerator
          // widget can override how copying is handled.
41 42 43 44 45 46 47 48
          CopyTextIntent: Action<CopyTextIntent>.overridable(defaultAction: defaultCopyAction, context: context),
        },
        child: Focus(
          autofocus: true,
          child: DefaultTextStyle.merge(
            style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            child: Text(text),
          ),
49 50 51 52 53 54
        ),
      ),
    );
  }
}

55 56
class VerificationCodeGenerator extends StatelessWidget {
  const VerificationCodeGenerator({ super.key });
57

58 59 60
  void _copy(CopyTextIntent intent) {
    debugPrint('Content copied');
    Clipboard.setData(const ClipboardData(text: '111222333'));
61 62 63 64 65
  }

  @override
  Widget build(BuildContext context) {
    return Actions(
66 67 68
      actions: <Type, Action<Intent>> { CopyTextIntent: CallbackAction<CopyTextIntent>(onInvoke: _copy) },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
69
        children: <Widget>[
70 71 72 73 74 75 76 77 78 79 80
          const Text('Press Ctrl-C to Copy'),
          const SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: const <Widget>[
              CopyableText(text: '111'),
              SizedBox(width: 5,),
              CopyableText(text: '222'),
              SizedBox(width: 5,),
              CopyableText(text: '333'),
            ],
81
          ),
82 83 84 85 86
        ],
      ),
    );
  }
}