Flutter: Textfield in overlay triggering rebuilds

Viewed 651

I can't seem to figure out why the code below prints built three times (calls State.build) after you hit the button to show the Overlay and focus the Textfield.

Now, I know that a MaterialApp inside another MaterialApp is not a good idea and that's the second part of the problem: Why won't the Keyboard (testing on a physical device with Android 8.1.0) appear when I remove the MaterialApp wrapped around the Scaffold and try to focus the Textfield? There is a MaterialApp at the root whose Overlay Overlay.of(context) should find.

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

void main() {
  SystemChrome.setEnabledSystemUIOverlays([]);
  runApp(
    MaterialApp(
      home: Scaffold(
        body: MyOtherApp()
      )
    )
  );
}

class MyAppState extends State<MyApp> {
  TextEditingController controller = TextEditingController();

  @override
    Widget build(BuildContext context) {
      controller.text = "placeholder";

      return MaterialApp(
        home: Scaffold(
          body: (){
            print("built");
            return TextField(
              controller: controller,
            );
          }()
        )
      );
    }
}

class MyApp extends StatefulWidget {
  @override
    State<StatefulWidget> createState() {
      return MyAppState();
    }
}

class MyOtherApp extends StatelessWidget {
  @override
    Widget build(BuildContext context) {
      return Center(
        child: FlatButton(
          child: Text(
            "show overlay",
          ),
          onPressed: () {
            Overlay.of(context).insert(
              OverlayEntry(
                builder: (context) {
                  return MyApp();
                }
              )
            );
          }
        )
      );
    }
}
1 Answers

In my case I put SystemChrome.setEnabledSystemUIOverlays([]); under the build instead in the main.

Related