如何在Flutter中使用OrientationBuilder避免当键盘打开时屏幕方向改变?

3

如何在 Flutter 中使用 OrientationBuilder 打开键盘时避免屏幕方向改变 ?

实际上,当键盘弹出时,即使我们没有旋转手机,OrientationBuilder 的方向属性也会更改为横向。

图像:

enter image description here

代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: OrientationBuilder(builder: (context, orientation) {
            var _children = [
              Expanded(
                  child: Center(
                      child: Text('Orientation : $orientation',
                          textAlign: TextAlign.center))),
              Flexible(
                  child: Container(color: Colors.blue, child: TextField())),
              Flexible(child: Container(color: Colors.yellow)),
            ];
            if (orientation == Orientation.portrait) {
              return Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: _children);
            } else {
              return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: _children);
            }
          })),
    );
  }
}

1个回答

1
当使用OrientationBuilder打开键盘时如何避免方向更改?在Scaffold小部件中将resizeToAvoidBottomInset设置为false;
图片:

enter image description here

代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          resizeToAvoidBottomInset: false, // Here
          body: SafeArea(
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: OrientationBuilder(builder: (context, orientation) {
                return Column(
                  children: [
                    Text('Orientation = $orientation',
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.bold)),
                    TextField(
                      decoration: InputDecoration(
                        hintText: 'tap me',
                      ),
                    )
                  ],
                );
              }),
            ),
          )),
    );
  }
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接