0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Flutter:Control+Enterで投稿できるTextField

Last updated at Posted at 2023-06-10

FlutterのMac/Windows/Linuxにおいて、改行できてかつControl+Enter(またはShift+Enter)で投稿できるTextFieldを作る方法です。検索してもドンピシャな例が意外と見つからなかったので共有します。

※riverpodを使っているのでConsumerWidgetになっています。適宜書き換えてください。

sample.dart
import 'dart:io' show Platform;

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends ConsumerWidget {
  MyHomePage({super.key});
  final TextEditingController _controller = TextEditingController();
  late final _sendMemoNode = FocusNode(onKey: (FocusNode node, RawKeyEvent e) {
    if (e.isControlPressed && e.logicalKey.keyLabel == 'Enter') {
    //shift+Enterにしたいときは e.isShiftPressed にする
      if (e is RawKeyDownEvent) {
        submit();
      }
      return KeyEventResult.handled;
    } else {
      return KeyEventResult.ignored;
    }
  });

  void submit() {
    final text = _controller.text;
    debugPrint(text);
    //ここにSubmitの処理を書く
    _controller.clear();
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      body: Center(
        child: TextField(
            controller: _controller,
            decoration: const InputDecoration(hintText: 'Enter Message'),
            onSubmitted: (_) =>
                {if (Platform.isIOS || Platform.isAndroid) submit()}, //スマホ版では普通にSubmitする
            focusNode: _sendMemoNode,
            keyboardType: TextInputType.multiline,
            minLines: 1,
            maxLines: 20),
      ),
    );
  }
}

実行結果↓

image.png

Control+Enterを押したときのログ↓

image.png

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?