繁体   English   中英

Flutter:如何调整这些按钮的大小

[英]Flutter: How to resize these buttons

我想创建这样的东西:

在此处输入图像描述

但很显然,我不是很成功!

在此处输入图像描述

如何调整 FlatButtons 的大小以填充整个容器,就像第一张图片一样? 我知道,容器中高度的解决方案不是很好,但这是另一个问题。

import 'package:flutter/material.dart';

class CalcButton extends StatelessWidget {
  //Constructor isn't important for you.

  @override
  Widget build(BuildContext context) {
    if (text == null) {
      return FlatButton(
          onPressed: () => {}, child: statelessWidget, color: backgroundColor);
    } else
      return FlatButton(
          onPressed: () => {},
          child: Text(text,
              style: TextStyle(fontSize: fontSize, color: textColor)),
          color: backgroundColor);
  }
}

我的小部件是从这里调用的:

 Widget numpad_structure(BuildContext context, var height) {
    return Padding(
        padding: const EdgeInsets.only(top: 25),
        child: Container(
          alignment: Alignment.bottomCenter,
          width: double.infinity,
          height: 550,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: numpad_background_color),
          child: numpad_buttons(context, height)
        ));
  }
  
  Widget numpad_buttons(BuildContext context, var height) {
    return Column(children: [
      Row(children: [
        CalcButton(text: "AC", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(backgroundColor: Colors.red, statelessWidget: Icon(Icons.backspace_outlined, size: numPadCharacterSize, color: textColor)),
        CalcButton(text: "%", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "÷", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor)
      ],
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,),
      Row(children: [
        CalcButton(text: "7", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "8", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "9", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "×", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor)
      ],
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,),
      Row(children: [
        CalcButton(text: "4", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "5", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "6", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "-", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor)
      ],
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,),
      Row(children: [
        CalcButton(text: "1", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "2", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "3", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "+", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor)
      ],
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,),
      Row(children: [
        CalcButton(text: ",", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "0", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "()", backgroundColor: Colors.red, fontSize: numPadCharacterSize, textColor: textColor),
        CalcButton(text: "=", backgroundColor: equal_button_background_color, fontSize: numPadCharacterSize, textColor: textColor)
      ],
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,)
    ],
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,);
  }```

使用这个完整的 UI示例

你的main.dart

import 'package:calculator_ui_example/colors.dart';
import 'package:calculator_ui_example/widget/button_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  static final String title = 'Calculator';

  @override
  Widget build(BuildContext context) => MaterialApp(
        debugShowCheckedModeBanner: false,
        title: title,
        theme: ThemeData(
          scaffoldBackgroundColor: MyColors.background1,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: MainPage(title: title),
      );
}

class MainPage extends StatefulWidget {
  final String title;

  const MainPage({
    @required this.title,
  });

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Colors.transparent,
          title: Container(
            margin: EdgeInsets.only(left: 8),
            child: Text(widget.title),
          ),
        ),
        body: SafeArea(
          child: Column(
            children: <Widget>[
              Expanded(child: buildResult()),
              Expanded(flex: 2, child: buildButtons())
            ],
          ),
        ),
      );

  Widget buildResult() => Container(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(
              '0',
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.white, fontSize: 36),
            ),
            const SizedBox(height: 24),
            Text(
              '0',
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.grey, fontSize: 18),
            ),
          ],
        ),
      );

  Widget buildButtons() => Container(
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: MyColors.background2,
          borderRadius: BorderRadius.vertical(top: Radius.circular(32)),
        ),
        child: Column(
          children: <Widget>[
            buildButtonRow('AC', '<', '', '÷'),
            buildButtonRow('7', '8', '9', '⨯'),
            buildButtonRow('4', '5', '6', '-'),
            buildButtonRow('1', '2', '3', '+'),
            buildButtonRow('0', '.', '', '='),
          ],
        ),
      );

  Widget buildButtonRow(
    String first,
    String second,
    String third,
    String fourth,
  ) {
    final row = [first, second, third, fourth];

    return Expanded(
      child: Row(
        children: row
            .map((text) => ButtonWidget(
                  text: text,
                  onClicked: () => print(text),
                  onClickedLong: () => print(text),
                ))
            .toList(),
      ),
    );
  }
}

button_widget.dart

import 'package:calculator_ui_example/colors.dart';
import 'package:calculator_ui_example/utils.dart';
import 'package:flutter/material.dart';

class ButtonWidget extends StatelessWidget {
  final String text;
  final VoidCallback onClicked;
  final VoidCallback onClickedLong;

  const ButtonWidget({
    Key key,
    @required this.text,
    @required this.onClicked,
    @required this.onClickedLong,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final color = getTextColor(text);
    final double fontSize = Utils.isOperator(text, hasEquals: true) ? 26 : 22;
    final style = TextStyle(
      color: color,
      fontSize: fontSize,
      fontWeight: FontWeight.bold,
    );

    return Expanded(
      child: Container(
        height: double.infinity,
        margin: EdgeInsets.all(6),
        child: ElevatedButton(
          onPressed: onClicked,
          onLongPress: onClickedLong,
          style: ElevatedButton.styleFrom(
            primary: MyColors.background3,
            elevation: 0,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
          ),
          child: text == '<'
              ? Icon(Icons.backspace_outlined, color: color)
              : Text(text, style: style),
        ),
      ),
    );
  }

  Color getTextColor(String buttonText) {
    switch (buttonText) {
      case '+':
      case '-':
      case '⨯':
      case '÷':
      case '=':
        return MyColors.operators;
      case 'AC':
      case '<':
        return MyColors.delete;
      default:
        return MyColors.numbers;
    }
  }
}

colors.dart

import 'package:flutter/material.dart';

class MyColors {
  static final Color background1 = Color(0xff22252d);
  static final Color background2 = Color(0xff292d36);
  static final Color background3 = Color(0xff272b33);
  static final Color operators = Color(0xfff57b7b);
  static final Color delete = Color(0xff26f4ce);
  static final Color numbers = Colors.white;
}

最后添加这个utils.dart

class Utils {
  static bool isOperator(String buttonText, {bool hasEquals = false}) {
    final operators = ['+', '-', '÷', '⨯', '.']..addAll(hasEquals ? ['='] : []);

    return operators.contains(buttonText);
  }
}

这是结果:

在此处输入图像描述

将您的按钮包裹在展开中:

import 'package:flutter/material.dart';

class CalcButton extends StatelessWidget {
  //Constructor isn't important for you.

  @override
  Widget build(BuildContext context) {
    if (text == null) {
      return Expanded(
        child: FlatButton(
            onPressed: () => {}, child: statelessWidget, color: backgroundColor),
      );
    } else
      return Expanded(
        child: FlatButton(
            onPressed: () => {},
            child: Text(text,
                style: TextStyle(fontSize: fontSize, color: textColor)),
            color: backgroundColor),
      );
  }
}

在我看来更好:

   @override
  Widget build(BuildContext context) {
    return GridView.count(
      childAspectRatio: 1.8, ///fiddle with this to get your desired height. 1.0 is a square.
      padding: const EdgeInsets.all(4),
      crossAxisSpacing: 4,
      mainAxisSpacing: 4,
      crossAxisCount: 4,
      children: <Widget>[
        CalcButton(),
        CalcButton(),
        CalcButton(),
        CalcButton(),
        CalcButton(),
        CalcButton(),
        ...
      ],
    );
  }

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM