调整大小按钮以适合不同的屏幕尺寸

时间:2019-09-23 20:56:27

标签: flutter dart

我试图根据不同的屏幕尺寸来调整下面的按钮的大小,但要保持相同的比例(即,文本和按钮的尺寸应成比例地变化,以便它们在所有屏幕上看起来都一样)。我正在使用AutoSizeText包根据屏幕大小调整文本大小,但是在较小的屏幕上文本似乎没有变小,这可能会导致按钮奇怪地调整大小。

[![按钮1] [1]] [1]-更大的屏幕 [![按钮2] [2]] [2]-较小的屏幕

我尝试使用mediaquery来调整按钮的高度和宽度,但这似乎不起作用。

有推荐的方法吗?

class PurchaseButton extends StatelessWidget {
  final Product product;

  PurchaseButton({Key key, @required this.product}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double deviceWidth = MediaQuery.of(context).size.width;

    Container(
      margin: EdgeInsets.symmetric(horizontal: 0.05 * deviceWidth),

    child: Row(
      children: <Widget>[

    Expanded(
      child: MaterialButton(
//      height: SizeConfig.blockSizeVertical * 6,

        onPressed: () async {
          await Provider.of<SubscriptionModel>(context).makePurchase(product);
        },
        child: Text('Join now! Only ${product.priceString}',
            style: Theme.of(context).textTheme.body1.copyWith(
                fontWeight: FontWeight.w600, fontSize: 0.03 * deviceWidth)),

        color: Theme.of(context).primaryColor,
      ),
      ),
    ],
    ),
    );
    return Container();
  }
}

1 个答案:

答案 0 :(得分:1)

许多方法可以做到,这是一个建议:

使用此小部件树包装您的小部件:

  • 容器:根据屏幕尺寸来控制宽度,
  • -:我们需要它来强制Expanded正常工作,
  • ---- 扩展:将其内容扩展到它拥有的整个空间,
  • ------ [您要扩展的小部件]
@override
Widget build(BuildContext context) {

  double deviceWidth = MediaQuery.of(context).size.width;
  double deviceHight = MediaQuery.of(context).size.height;

  Container(
      // If the button size(Row) is 90% then we give margin 5% + 5% like this
      margin: EdgeInsets.symmetric(horizontal: 0.05 * deviceWidth),

      // We need a Row in order to "Expanded" to work
      child: Row(
        children: <Widget>[
          // Use "Expanded" if you want the button to fill the Row's size
          // Use "Flexible" if you want the button to fit the text inside size.
          Expanded(
            child: MaterialButton(
              onPressed: () {
                print('Hi');
              },
              child: Text(
                'Join now! Only...',
                style: Theme.of(context)
                    .textTheme
                    .body1
                    .copyWith(fontWeight: FontWeight.w600),
              ),
              color: Theme.of(context).primaryColor,
            ),
          ),
        ],
      ),
    );

关于AutoSizeText,它考虑的是文本容器的大小,而不是屏幕的大小,我的建议是使用常规的Text(..)小部件,其字体大小取自MediaQuery.of(context).size.width

例如

child: Text(
   'Join now! Only...',
   style: Theme.of(context)
          .textTheme
          .body1
          .copyWith(
             fontWeight: FontWeight.w600,
             fontSize: 0.03 * deviceWidth,
          ),
   ),