Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter AlertDialog Moves Up When Keyboard Appears

Tags:

flutter

dart

I’m running into an issue where my AlertDialog moves when the keyboard appears. I want it to stay fixed in place, but right now, it shifts up when the keyboard comes in.

I’ve tried wrapping it in SingleChildScrollView, but it still moves. I've also tried resizeToAvoidBottomInset: false but I think it's only applied to the top-level Scaffold and since showDialog creates its own overlay, the surrounding Scaffold in my last code doesn’t actually affect it. I've also tried a workaround involving MediaQuery.removeViewInsets but that causes other issues.

Is there a way to keep the dialog fixed exactly in place when the keyboard appears? Sharing a simplified version of my code below:

void _showAddBoxDialog() {
  TextEditingController nameController = TextEditingController();
  showDialog(
    context: context,
    builder: (BuildContext context) => Dialog(
      backgroundColor: Colors.transparent,
      child: AlertDialog(
        backgroundColor: const Color(0xFFF9F9F9),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.0),
        ),
        content: TextField(
          controller: nameController,
          autofocus: true,
          textInputAction: TextInputAction.done,
          decoration: const InputDecoration(hintText: 'Enter box name'),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              if (nameController.text.isNotEmpty) {
                // Save action here
                Navigator.pop(context);
              }
            },
            child: const Text('Add'),
          ),
        ],
      ),
    ),
  );
}
like image 964
Bob E Avatar asked Dec 01 '25 18:12

Bob E


1 Answers

The AlertDialog uses MediaQuery.viewInsetsOf(context) internally, /material/dialog.dart#L244

You can use Material and the way you like to decorate

showDialog(
  context: context,
  builder: (BuildContext context) => Center(
    child: Material(
      color: const Color(0xFFF9F9F9),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.0),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          TextField(
            controller: nameController,
            autofocus: true,
            textInputAction: TextInputAction.done,
            decoration: const InputDecoration(hintText: 'Enter box name'),
          ),
        ],
      ),
    ),
  ),
);
like image 153
Yeasin Sheikh Avatar answered Dec 04 '25 07:12

Yeasin Sheikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!