【问题标题】:Flutter: How to resize these buttonsFlutter:如何调整这些按钮的大小
【发布时间】:2021-04-05 12:00:15
【问题描述】:

我想创建这样的东西:

但显然,我不是很成功!

如何调整 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,);
  }```

【问题讨论】:

    标签: android flutter dart flutter-dependencies


    【解决方案1】:

    使用这个完整的 UI sample

    你的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);
      }
    }
    

    这是结果:

    【讨论】:

    • 感谢您的解决方案,它很棒,还有很多新东西要学习。我很快就会接受这个答案,我只需要了解所有内容:D 是否可以使用这个按钮,它们之间没有空格,就像图片上的那样?
    • 这很有趣。
    • 是的,您可以在button_widget.dart 中删除margin: EdgeInsets.all(6) 这一行,或者使用您的保证金。
    【解决方案2】:

    在我看来更好:

       @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(),
            ...
          ],
        );
      }
    

    【讨论】:

      【解决方案3】:

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

      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),
            );
        }
      }
      

      【讨论】:

      • 首先感谢您的回答。您的解决方案仅在一个方向上起作用:prnt.sc/wbp7px 我应该尝试将完整的 Row 放入扩展的小部件中吗?
      • “我应该尝试将完整的 Row 放入扩展的小部件中吗?”我自己的想法,并没有真正的帮助。
      • @Simon2215 它应该可以将每一行都展开
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 2011-05-30
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多