Search code examples
flutterdart

Flutter AlertDialog Moves Up When Keyboard Appears


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'),
          ),
        ],
      ),
    ),
  );
}

Solution

  • 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'),
              ),
            ],
          ),
        ),
      ),
    );