Ctrl-z shortcut interfering with TextField's default Ctrl-z

20 Views Asked by At

What I'm trying to do : I want my app to have a ctrl-z shortcut where it'll revert the state to the previous one (undo). We'll call this app's ctrl-z.

If the focus is in a TextField, however, I want the app's ctrl-z to be ignored, and the default ctrl-z feature of a TextField to take over.

The problem : Whenever I bind a ctrl-z shortcut to a parent of a TextField, the TextField's ctrl-z default behaviour is ignored. I can easily have the app's ctrl-z not called if the TextField is in focus with DoNothingAndStopPropagationIntent, but I cannot get the TextField's default ctrl-z behaviour to be called while the parent defines a ctrl-z shortcut.

Sample app showcasing the problem :

You can try to change the shortcut to ctrl-A, and see that doing that, the default ctrl-z behaviour of the TextField starts working again.

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

void main() {
  runApp(const MaterialApp(
    home: SamplePage(),
  ));
}

class SamplePage extends StatefulWidget {
  const SamplePage({Key? key}) : super(key: key);

  @override
  State<SamplePage> createState() => _SamplePageState();
}

class _SamplePageState extends State<SamplePage> {
  final TextEditingController _textCtrl1 = TextEditingController();
  final TextEditingController _textCtrl2 = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return CallbackShortcuts(
      bindings: {
        LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyZ): () {
          print("App's Ctrl-z : Undo");
        },
      },
      child: FocusScope(
        child: Scaffold(
          appBar: AppBar(
            title: const Text('Paramètres'),
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          ),
          body: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                Focus(
                  onFocusChange: (value) =>
                      print('Text Field 1 - Focus : $value'),
                  child: TextFormField(
                    controller: _textCtrl1,
                    decoration: const InputDecoration(
                      labelText: 'Text Field 1',
                    ),
                  ),
                ),
                Focus(
                  onFocusChange: (value) =>
                      print('Text Field 2 - Focus : $value'),
                  child: TextFormField(
                    controller: _textCtrl2,
                    decoration: const InputDecoration(
                      labelText: 'Text Field 2',
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

0

There are 0 best solutions below