📜  使用Flutter 的简单计算器应用程序

📅  最后修改于: 2021-09-23 06:25:17             🧑  作者: Mango

Flutter SDK 是一个开源软件开发工具包,用于构建原生编译的漂亮 UI。在本文中,我们将构建一个简单的计算器应用程序,它可以根据用户输入执行基本的算术运算,如加法、减法、乘法或除法。制作此应用程序将使您对flutter和dart基础知识有一个很好的修订。涵盖的概念是:

  • 在屏幕上显示小部件。
  • Gridview.builder
  • 函数编写
  • 如果和其他在dart

按照以下步骤来实现简单的计算器。让我们开始吧。

第 1 步:创建Flutter应用程序

打开终端/命令提示符。将目录更改为您选择的并运行flutter 。在 VS Code 中打开计算器应用 或安卓工作室。

第 2 步:编码计算器应用程序

在 Lib 文件夹中,有一个 main. dart文件已经存在。现在在同一个文件夹中创建一个名为按钮的新文件。dart。开始。dart文件。创建MyApp类并使其成为StatelessWidget 。添加一组要显示的按钮。为按钮设置背景颜色、文本颜色、 onTapped功能。编写一个函数来计算答案

Dart
import 'package:flutter/material.dart';
import 'buttons.dart';
import 'package:math_expressions/math_expressions.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    ); // MaterialApp
  }
}
  
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}
  
class _HomePageState extends State {
  var userInput = '';
  var answer = '';
  
  // Array of button
  final List buttons = [
    'C',
    '+/-',
    '%',
    'DEL',
    '7',
    '8',
    '9',
    '/',
    '4',
    '5',
    '6',
    'x',
    '1',
    '2',
    '3',
    '-',
    '0',
    '.',
    '=',
    '+',
  ];
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text("Calculator"),
      ), //AppBar
      backgroundColor: Colors.white38,
      body: Column(
        children: [
          Expanded(
            child: Container(
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Container(
                      padding: EdgeInsets.all(20),
                      alignment: Alignment.centerRight,
                      child: Text(
                        userInput,
                        style: TextStyle(fontSize: 18, color: Colors.white),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.all(15),
                      alignment: Alignment.centerRight,
                      child: Text(
                        answer,
                        style: TextStyle(
                            fontSize: 30,
                            color: Colors.white,
                            fontWeight: FontWeight.bold),
                      ),
                    )
                  ]),
            ),
          ),
          Expanded(
            flex: 3,
            child: Container(
              child: GridView.builder(
                  itemCount: buttons.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 4),
                  itemBuilder: (BuildContext context, int index) {
                    // Clear Button
                    if (index == 0) {
                      return MyButton(
                        buttontapped: () {
                          setState(() {
                            userInput = '';
                            answer = '0';
                          });
                        },
                        buttonText: buttons[index],
                        color: Colors.blue[50],
                        textColor: Colors.black,
                      );
                    }
  
                    // +/- button
                    else if (index == 1) {
                      return MyButton(
                        buttonText: buttons[index],
                        color: Colors.blue[50],
                        textColor: Colors.black,
                      );
                    }
                    // % Button
                    else if (index == 2) {
                      return MyButton(
                        buttontapped: () {
                          setState(() {
                            userInput += buttons[index];
                          });
                        },
                        buttonText: buttons[index],
                        color: Colors.blue[50],
                        textColor: Colors.black,
                      );
                    }
                    // Delete Button
                    else if (index == 3) {
                      return MyButton(
                        buttontapped: () {
                          setState(() {
                            userInput =
                                userInput.substring(0, userInput.length - 1);
                          });
                        },
                        buttonText: buttons[index],
                        color: Colors.blue[50],
                        textColor: Colors.black,
                      );
                    }
                    // Equal_to Button
                    else if (index == 18) {
                      return MyButton(
                        buttontapped: () {
                          setState(() {
                            equalPressed();
                          });
                        },
                        buttonText: buttons[index],
                        color: Colors.orange[700],
                        textColor: Colors.white,
                      );
                    }
  
                    //  other buttons
                    else {
                      return MyButton(
                        buttontapped: () {
                          setState(() {
                            userInput += buttons[index];
                          });
                        },
                        buttonText: buttons[index],
                        color: isOperator(buttons[index])
                            ? Colors.blueAccent
                            : Colors.white,
                        textColor: isOperator(buttons[index])
                            ? Colors.white
                            : Colors.black,
                      );
                    }
                  }), // GridView.builder
            ),
          ),
        ],
      ),
    );
  }
  
  bool isOperator(String x) {
    if (x == '/' || x == 'x' || x == '-' || x == '+' || x == '=') {
      return true;
    }
    return false;
  }
  
// function to calculate the input operation
  void equalPressed() {
    String finaluserinput = userInput;
    finaluserinput = userInput.replaceAll('x', '*');
  
    Parser p = Parser();
    Expression exp = p.parse(finaluserinput);
    ContextModel cm = ContextModel();
    double eval = exp.evaluate(EvaluationType.REAL, cm);
    answer = eval.toString();
  }
}


Dart
import 'package:flutter/material.dart';
  
// creating Stateless Wideget for buttons
class MyButton extends StatelessWidget {
    
  // declaring variables 
  final color;
  final textColor;
  final String buttonText;
  final buttontapped;
  
  //Constructor
  MyButton({this.color, this.textColor, this.buttonText, this.buttontapped});
  
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: buttontapped,
      child: Padding(
        padding: const EdgeInsets.all(0.2),
        child: ClipRRect(
          // borderRadius: BorderRadius.circular(25),
          child: Container(
            color: color,
            child: Center(
              child: Text(
                buttonText,
                style: TextStyle(
                  color: textColor,
                  fontSize: 25,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}


在Flutter主要。 dart文件是代码开始执行的入口点。在主要。 dart文件首先导入了材料设计包以及math_expressions按钮。dart文件。然后创建了一个函数runApp ,参数为MyApp 。类MyApp的这是一个无状态的小部件的声明后,班MyApp的状态已经奠定了。

第 3 步:构建按钮。dart

按钮中。已经在dart中导入的dart 。在 dart文件中,我们使用构造函数声明将在整个程序中使用的变量。颜色、文本颜色、按钮文本和点击按钮的功能将在 main.js 中实现。dart文件

Dart

import 'package:flutter/material.dart';
  
// creating Stateless Wideget for buttons
class MyButton extends StatelessWidget {
    
  // declaring variables 
  final color;
  final textColor;
  final String buttonText;
  final buttontapped;
  
  //Constructor
  MyButton({this.color, this.textColor, this.buttonText, this.buttontapped});
  
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: buttontapped,
      child: Padding(
        padding: const EdgeInsets.all(0.2),
        child: ClipRRect(
          // borderRadius: BorderRadius.circular(25),
          child: Container(
            color: color,
            child: Center(
              child: Text(
                buttonText,
                style: TextStyle(
                  color: textColor,
                  fontSize: 25,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

第 4 步:在 pubspec.yaml 文件中添加依赖项

为了使过程更容易,我们使用了math_expressions: ^2.0.0包,它在 main 中导入。 dart文件来处理所有计算和运行时错误异常。

添加 math_expressions : ^2.0.0 依赖项

输出:

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!