반응형

To make a TextField in a showModalBottomSheet go up above the keyboard when it is focused, you can use the Padding widget with MediaQuery.of(context).viewInsets to dynamically adjust the padding based on the keyboard's visibility. Here's how you can achieve this:

  1. Wrap the content of the showModalBottomSheet in a Padding widget.
  2. Set the padding using MediaQuery.of(context).viewInsets to ensure it adjusts when the keyboard is shown.

Here is a complete example:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Modal Bottom Sheet Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              showModalBottomSheet(
                context: context,
                isScrollControlled: true, // This makes the bottom sheet take full height when the keyboard is open
                builder: (BuildContext context) {
                  return Padding(
                    padding: MediaQuery.of(context).viewInsets, // Adjust the padding based on the keyboard visibility
                    child: Container(
                      padding: EdgeInsets.all(16.0),
                      child: Column(
                        mainAxisSize: MainAxisSize.min, // Make the bottom sheet size to its content
                        children: [
                          TextField(
                            decoration: InputDecoration(labelText: 'Enter text'),
                          ),
                          SizedBox(height: 16.0),
                          ElevatedButton(
                            onPressed: () {
                              Navigator.pop(context);
                            },
                            child: Text('Close'),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              );
            },
            child: Text('Show Modal Bottom Sheet'),
          ),
        ),
      ),
    );
  }
}

In this example:

  • isScrollControlled: true makes the bottom sheet take the full height when the keyboard is open.
  • Padding with MediaQuery.of(context).viewInsets ensures the bottom sheet adjusts its padding based on the keyboard visibility, so the TextField moves up above the keyboard when focused.

This approach ensures a smooth experience for users when interacting with TextField inside a showModalBottomSheet.

반응형

+ Recent posts