Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why rebuilding when TextField tapped? #72988

Closed
buddypia opened this issue Dec 27, 2020 · 8 comments
Closed

Why rebuilding when TextField tapped? #72988

buddypia opened this issue Dec 27, 2020 · 8 comments
Labels
in triage Presently being triaged by the triage team

Comments

@buddypia
Copy link

If remove the MediaQuery.of(context).size code, it will not rebuild.

this is my code.

import 'dart:async';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Example',
      home: ExamplePage(),
    );
  }
}

class ExamplePage extends StatelessWidget {
  Future<Size> init(BuildContext context) async {
    print("init");
    return MediaQuery.of(context).size;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: FutureBuilder(
            future: init(context),
            builder: (BuildContext context, AsyncSnapshot<Size> snapshot) {
              if (snapshot.hasError) {
                return Text(snapshot.error);
              } else if (snapshot.connectionState == ConnectionState.waiting ||
                  !snapshot.hasData) {
                return CircularProgressIndicator();
              } else if (snapshot.data == null) {
                return Text("snapshot.data == null");
              }

              return Center(child: TextField());
            }));
  }
}
Logs

❯ flutter doctor -v
[✓] Flutter (Channel stable, 1.22.5, on Mac OS X 10.15.7 19H15 darwin-x64, locale ja)
• Flutter version 1.22.5 at /Users/LeeJunHo/dev/flutter/flutter
• Framework revision 7891006 (2 weeks ago), 2020-12-10 11:54:40 -0800
• Engine revision ae90085a84
• Dart version 2.10.4

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
• Android SDK at /Users/LeeJunHo/dev/env/sdk
• Platform android-30, build-tools 29.0.2
• ANDROID_HOME = /Users/LeeJunHo/dev/env/sdk
• ANDROID_SDK_ROOT = /Users/LeeJunHo/dev/env/sdk
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 12.2, Build version 12B45b
• CocoaPods version 1.10.0

[✓] Android Studio (version 4.0)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 47.1.2
• Dart plugin version 193.7361
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

[✓] IntelliJ IDEA Community Edition (version 2020.3)
• IntelliJ at /Applications/IntelliJ IDEA CE.app
• Flutter plugin installed
• Dart plugin version 203.6912

[✓] VS Code (version 1.52.1)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.18.0

[✓] Connected device (1 available)
• iPhone 11 (mobile) • 8715568A-E61C-4527-9401-2E31F0C25404 • ios • com.apple.CoreSimulator.SimRuntime.iOS-14-2 (simulator)

• No issues found!

@iapicca
Copy link
Contributor

iapicca commented Dec 27, 2020

@shoridevel
I fail to understand the use case of treating MediaQuery.of(context).size as Future
regardless I do experience the described behavior on mobile, but not on web

flutter run -v
[  +96 ms] Syncing files to device Pixel 3a...
[   +1 ms] <- reset
[        ] Compiling dart to kernel with 0 updated files
[   +1 ms] <- recompile package:issue/main.dart 42a20d5c-9b0f-4b66-b045-90e6dde4b33d
[        ] <- 42a20d5c-9b0f-4b66-b045-90e6dde4b33d
[  +85 ms] Updating files.
[        ] DevFS: Sync finished
[   +1 ms] Syncing files to device Pixel 3a... (completed in 89ms)
[        ] Synced 0.0MB.
[        ] <- accept
[  +30 ms] Connected to _flutterView/0x77fe15ff20.
[   +2 ms] Flutter run key commands.
[   +1 ms] r Hot reload. 🔥🔥🔥
[        ] R Hot restart.
[        ] h Repeat this help message.
[        ] d Detach (terminate "flutter run" but leave application running).
[        ] c Clear the screen
[        ] q Quit (terminate the application on the device).
[        ] An Observatory debugger and profiler on Pixel 3a is available at: http://127.0.0.1:44711/oNf4Wl8Gg-c=/
[        ] Running with unsound null safety
[        ] For more information see https://dart.dev/null-safety/unsound-null-safety
[ +275 ms] I/flutter ( 9701): init
[+9847 ms] W/IInputConnectionWrapper( 9701): getExtractedText on inactive InputConnection
[        ] W/IInputConnectionWrapper( 9701): getTextBeforeCursor on inactive InputConnection
[  +54 ms] W/IInputConnectionWrapper( 9701): getExtractedText on inactive InputConnection
[        ] W/IInputConnectionWrapper( 9701): getTextBeforeCursor on inactive InputConnection
[  +18 ms] W/IInputConnectionWrapper( 9701): getExtractedText on inactive InputConnection
[        ] W/IInputConnectionWrapper( 9701): getTextBeforeCursor on inactive InputConnection
[   +6 ms] E/SpannableStringBuilder( 9701): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
[ +175 ms] I/chatty  ( 9701): uid=10407(com.example.issue) identical 2 lines
[   +2 ms] E/SpannableStringBuilder( 9701): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
[        ] I/flutter ( 9701): init
[  +76 ms] I/flutter ( 9701): init
[+1978 ms] I/chatty  ( 9701): uid=10407(com.example.issue) 1.ui identical 6 lines
[        ] I/flutter ( 9701): init
[+7035 ms] W/IInputConnectionWrapper( 9701): getExtractedText on inactive InputConnection
[   +1 ms] W/IInputConnectionWrapper( 9701): getTextBeforeCursor on inactive InputConnection
[  +45 ms] E/SpannableStringBuilder( 9701): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
[  +69 ms] I/chatty  ( 9701): uid=10407(com.example.issue) identical 2 lines
[   +1 ms] E/SpannableStringBuilder( 9701): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
[        ] I/flutter ( 9701): init
[ +842 ms] I/chatty  ( 9701): uid=10407(com.example.issue) 1.ui identical 7 lines
[        ] I/flutter ( 9701): init
[+4030 ms] DevFS: Deleting filesystem on the device (file:///data/user/0/com.example.issue/code_cache/issueXTXFEH/issue/)
[  +33 ms] DevFS: Deleted filesystem on the device (file:///data/user/0/com.example.issue/code_cache/issueXTXFEH/issue/)
[ +407 ms] Failure in ext.flutter.exit: ext.flutter.exit: (-32000) Bad state: The client closed with pending request "ext.flutter.exit".

[   +9 ms] Service protocol connection closed.
[        ] Application finished.
[   +3 ms] executing: /home/francesco/Android/Sdk/platform-tools/adb -s 965AY0WP5C forward --list
[   +8 ms] Exit code 0 from: /home/francesco/Android/Sdk/platform-tools/adb -s 965AY0WP5C forward --list
[        ] 965AY0WP5C tcp:35507 tcp:38641
[   +1 ms] executing: /home/francesco/Android/Sdk/platform-tools/adb -s 965AY0WP5C forward --remove tcp:35507
[   +8 ms] executing: /home/francesco/Android/Sdk/platform-tools/adb -s 965AY0WP5C forward --list
[   +7 ms] Exit code 0 from: /home/francesco/Android/Sdk/platform-tools/adb -s 965AY0WP5C forward --list
[        ] "flutter run" took 193,616ms.
[ +254 ms] ensureAnalyticsSent: 251ms
[   +3 ms] Running shutdown hooks
[        ] Shutdown hook priority 4
[   +2 ms] Shutdown hooks complete
[   +1 ms] exiting with code 0
flutter run -d chrome -v
[ +215 ms] Launching lib/main.dart on Chrome in debug mode...
[ +111 ms] Updating assets
[ +115 ms] Waiting for connection from debug service on Chrome...
[  +53 ms] Found plugin integration_test at /home/francesco/snap/flutter/common/flutter/packages/integration_test/
[  +40 ms] Found plugin integration_test at /home/francesco/snap/flutter/common/flutter/packages/integration_test/
[  +43 ms] <- reset
[   +6 ms] /home/francesco/snap/flutter/common/flutter/bin/cache/dart-sdk/bin/dart --disable-dart-dev
/home/francesco/snap/flutter/common/flutter/bin/cache/artifacts/engine/linux-x64/frontend_server.dart.snapshot --sdk-root /home/francesco/snap/flutter/common/flutter/bin/cache/flutter_web_sdk/
--incremental --target=dartdevc --debugger-module-names --experimental-emit-debug-metadata --output-dill /tmp/flutter_tools.DXIPQO/flutter_tool.UXTJVN/app.dill --libraries-spec
file:///home/francesco/snap/flutter/common/flutter/bin/cache/flutter_web_sdk/libraries.json --packages /home/francesco/projects/issue/.dart_tool/package_config.json -Ddart.vm.profile=false
-Ddart.vm.product=false --enable-asserts --track-widget-creation --filesystem-root /tmp/flutter_tools.DXIPQO/flutter_tools.HLRXPQ --filesystem-scheme org-dartlang-app --initialize-from-dill
build/fbbe6a61fb7a1de317d381f8df4814e5.cache.dill.track.dill --platform file:///home/francesco/snap/flutter/common/flutter/bin/cache/flutter_web_sdk/kernel/flutter_ddc_sdk.dill --no-sound-null-safety
[  +12 ms] <- compile org-dartlang-app:/web_entrypoint.dart
[+21075 ms] Waiting for connection from debug service on Chrome... (completed in 21.2s)
[   +1 ms] Synced 28.6MB.
[        ] <- accept
[        ] Caching compiled dill
[ +179 ms] Using Google Chrome 87.0.4280.88 

[ +723 ms] [CHROME]:
[   +1 ms] [CHROME]:DevTools listening on ws://127.0.0.1:44931/devtools/browser/d9f8b470-fcb9-48d5-afa8-272989a0ef9e
[+2429 ms] DwdsInjector: Received request for entrypoint at http://localhost:34675/main_module.bootstrap.js
[   +5 ms] MetadataProvider: Loading debug metadata...
[  +15 ms] MetadataProvider: Loaded debug metadata
[  +13 ms] DwdsInjector: Injected debugging metadata for entrypoint at http://localhost:34675/main_module.bootstrap.js
[+3344 ms] DevHandler: Debug service listening on ws://127.0.0.1:43735/F8K2wOu8vNA=/ws

[   +8 ms] Debug service listening on ws://127.0.0.1:43735/F8K2wOu8vNA=/ws
[        ] Running with unsound null safety
[        ] For more information see https://dart.dev/null-safety/unsound-null-safety
[   +1 ms] Warning: Flutter's support for web development is not stable yet and hasn't
[        ] been thoroughly tested in production environments.
[        ] For more information see https://flutter.dev/web
[        ] 🔥  To hot restart changes while running, press "r" or "R".
[   +1 ms] For a more detailed help message, press "h". To quit, press "q".
[ +496 ms] init
[+150576 ms] DevHandler: Stopped debug service on ws://127.0.0.1:32885

[ +367 ms] Application finished.
[   +3 ms] "flutter run" took 180,369ms.
[ +255 ms] ensureAnalyticsSent: 252ms
[   +4 ms] Running shutdown hooks
[   +1 ms] Shutdown hook priority 4
[ +149 ms] Shutdown hooks complete
[        ] exiting with code 0
doctor
[✓] Flutter (Channel master, 1.26.0-2.0.pre.137, on Linux, locale en_US.UTF-8)
    • Flutter version 1.26.0-2.0.pre.137 at /home/francesco/snap/flutter/common/flutter
    • Framework revision 8f5d0371af (26 hours ago), 2020-12-26 11:07:36 +0330
    • Engine revision f5364860ab
    • Dart version 2.12.0 (build 2.12.0-179.0.dev)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /home/francesco/Android/Sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: /usr/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_275-8u275-b01-0ubuntu1~20.04-b01)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
    • cmake version 3.10.2
    • ninja version 1.8.2
    • pkg-config version 0.29.1

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/linux#android-setup for detailed instructions).

[✓] Connected device (2 available)
    • Linux (desktop) • linux  • linux-x64      • Linux
    • Chrome (web)    • chrome • web-javascript • Google Chrome 87.0.4280.88

! Doctor found issues in 1 category.

I believe this should be investigated

@pingbird
Copy link
Member

pingbird commented Dec 27, 2020

This is intended behavior as opening the keyboard changes the dimensions of the MediaQuery, specifically the viewInsets, padding, and viewPadding.

Could you elaborate more on what you are trying to do and the expected behavior?

@pingbird pingbird added in triage Presently being triaged by the triage team waiting for customer response The Flutter team cannot make further progress on this issue until the original reporter responds labels Dec 27, 2020
@iapicca
Copy link
Contributor

iapicca commented Dec 27, 2020

@PixelToast
I believe the behavior should be consistent between mobile and web

@buddypia
Copy link
Author

@PixelToast My issue has two problems.

  1. I need to get the screen size in init method for image processing. but TextField is rebuilding when i tapped. again init method called.
  2. The keyboard appears and then disappears immediately.

@no-response no-response bot removed the waiting for customer response The Flutter team cannot make further progress on this issue until the original reporter responds label Dec 27, 2020
@pingbird
Copy link
Member

The reason why the keyboard is disappearing is because your FutureBuilder is being used in an unsafe manner, regardless, the proper way of obtaining the size of the screen is:

class _ExampleState extends State<Example> {
  Size size;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final newSize = MediaQuery.of(context).size;
    if (size != newSize) {
      size = newSize;
      // Do stuff with size
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Or, if you don't care about listening to changes in the size of the screen it can be accessed directly through dart:ui's window singleton.

@pingbird
Copy link
Member

@iapicca The difference in behavior comes from the fact that MediaQuery changes when the keyboard opens, you would observe the same behavior on mobile with a physical keyboard rather than an on-screen one.

@buddypia
Copy link
Author

@PixelToast Thanks. This is the way I found the solution to the problem.

final size = window.physicalSize / window.devicePixelRatio;

@github-actions
Copy link

github-actions bot commented Aug 8, 2021

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Aug 8, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
in triage Presently being triaged by the triage team
Projects
None yet
Development

No branches or pull requests

3 participants