7
1

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 3 years have passed since last update.

[Flutter] ProviderパターンでTextFieldのイベントを扱う

Last updated at Posted at 2020-08-23

2021/1/11 追記

こちらの記事が本記事の改善版になりますので参考にしてください。

Statelessのように使いたい

TextFieldウィジェットのイベント監視にはControllerを使って,Statefulにする必要があります。
ProviderパターンではできるだけStatefulWidgetを使わないようにしたいので,下記のようにしてGestureDetectorのonTapのように扱えるようにしました。
どなたかのお力になれば。。

class EventListeningTextField extends StatefulWidget {
  EventListeningTextField({
    this.onChanged,
    this.onEditingCompleted,
    this.initialValue,
    this.inputDecoration,
  });
  Function(String) onChanged;
  Function(String) onEditingCompleted;
  String initialValue = '';
  InputDecoration inputDecoration;

  @override
  _EventListeningTextFieldState createState() =>
      _EventListeningTextFieldState(onChanged, onEditingCompleted, initialValue, inputDecoration);
}

class _EventListeningTextFieldState extends State<EventListeningTextField> {
  _EventListeningTextFieldState(
    this.onChanged,
    this.onEditingCompleted,
    this.initialValue,
    this.inputDecoration,
  );

  Function(String) onChanged;
  Function(String) onEditingCompleted;
  String initialValue = '';
  InputDecoration inputDecoration;
  final _textEditingController = TextEditingController();

  @override
  void initState() {
    _textEditingController.text = initialValue;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: TextField(
        controller: _textEditingController,
        onChanged: onChanged,
        onEditingComplete: () {
          onEditingCompleted(_textEditingController.text);
        },
        onSubmitted: (String value) {
          FocusScope.of(context).unfocus(); // キーボードを閉じる
        },
        decoration: inputDecoration,
      ),
    );
  }
}
7
1
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
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?