Prevent background from scrolling when using keyboard in Flutter

Viewed 403

I would like to have background scroll to focus the Textfield, but have the background image maintain it's position/aspect ratio.

What I have tried:

  • Wrapped my Scaffold in a Container with a BoxDecoration containing the background image
  • Wrapped my Scaffold with a stack, which included the image as the background
  • Disabled resizeToAvoidBottomInset in my Scaffold

Using the first and third option listed:

class LoginPage extends BasePage {
  LoginPage({Key? key}) : super(key, configTypes: [ConfigurationType.login]);
  
  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends BaseState<LoginPage> with BasicPage {
  @override
  Widget body() {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: ExactAssetImage(Assets.bgLogin), // Assets is constant to filepath
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.transparent, // To see background image
        body: SafeArea(
          child: ... // Contains textfield/other UI elements
        ),
      ),
    );
  }
}

Below is a demo of the background scrolling:

Background-scrolling.gif

1 Answers

I think you should return the Scaffold with your Container inside it. You are preventing the image to scroll on the Scaffold but not the scrolling of the parent Countainer.

class _LoginPageState extends BaseState<LoginPage> with BasicPage {
  @override
  Widget body() {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.transparent, // To see background image
        body: SafeArea(
          child: Container(
        decoration: const BoxDecoration(
        image: DecorationImage(
          image: ExactAssetImage(Assets.bgLogin), // Assets is constant to filepath
          fit: BoxFit.cover,
        ),
      ),
      child: ... // Contains textfield/other UI elements
        ),
      ),
    );
  }
Related