Widgets tree rebuild using FocusScope.of(context).unfocus()
Asked Answered
P

2

7

I have this example:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(30),
          child: GestureDetector(
            onTap: () {
              print('Hide keyboard!!!');
              FocusScope.of(context).unfocus();
            },
            child: Column(
              children: [
                Text(DateTime.now().toIso8601String()),
                TextFormField()
              ],
            ),
          ),
        ),
      ),
    );
  }

When the keyboard appears or is hidden it causes the widget to rebuild. Why does this happen?

Primula answered 31/8, 2020 at 7:11 Comment(0)
D
10

Actually, I couldn't find the reason behind the rebuild after using

FocusScope.of(context).unfocus();

But This one will help you to stop rebuild the widget.

FocusManager.instance.primaryFocus.unfocus();

It's working on my application.

Diphenylamine answered 31/8, 2021 at 11:24 Comment(1)
This is working for me with TextFormField as well ... using FocusScope.of(context).unfocus(); I would see random widget tree redraws and could even sometimes get into a state where it wasn't possible to re-focus the widget.Jonajonah
T
0

https://api.flutter.dev/flutter/widgets/FocusNode/unfocus.html

The example in documentation use primaryFocus.unfocus way.

OutlinedButton(
              child: const Text('UNFOCUS'),
              onPressed: () {
                setState(() {
                  primaryFocus!.unfocus(disposition: disposition);
                });
              },
            ),
Turnedon answered 4/3 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.