flutter写的一个计算器并保存历史记录

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'dart:math' as math;


void main() {
  runApp(CalculatorApp());
}

class CalculatorApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Calculator',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CalculatorScreen(),
    );
  }
}

class CalculatorScreen extends StatefulWidget {
  @override
  _CalculatorScreenState createState() => _CalculatorScreenState();
}

class _CalculatorScreenState extends State<CalculatorScreen> {
  String _output = "0";
  double _num1 = 0;
  double _num2 = 0;
  String _operator = "";
  String _displayText = "";
  List<String> _history = [];

  Future<void> _saveHistory() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setStringList('history', _history);
    print('History saved!');
  }

  Future<void> _loadHistory() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String>? history = prefs.getStringList('history');
    if (history != null) {
      setState(() {
        _history = history;
      });
    }
  }

  Future<void> _clearHistory() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove('history');
    setState(() {
      _history = [];
    });
    print('History cleared!');
  }

  void _buttonPressed(String buttonText) {
    setState(() {
      if (buttonText == "C") {
        _output = "0";
        _num1 = 0;
        _num2 = 0;
        _operator = "";
        _displayText = "";
      } else if (buttonText == "+" ||
          buttonText == "-" ||
          buttonText == "x" ||
          buttonText == "÷") {
        _num1 = double.parse(_output);
        _operator = buttonText;
        _displayText = "$_output $buttonText";
        _output = "0";
      } else if (buttonText == "=") {
        _num2 = double.parse(_output);
        double result = 0;
        if (_operator == "+") {
          result = _num1 + _num2;
        }
        if (_operator == "-") {
          result = _num1 - _num2;
        }
        if (_operator == "x") {
          result = _num1 * _num2;
        }
        if (_operator == "÷") {
          result = _num1 / _num2;
        }
        _output = result.toString();
       // _displayText = "";
        //_operator = "";

        // 添加历史记录
        String historyItem = "$_num1 $_operator $_num2 = $_output";
        _history.add(historyItem);
        _saveHistory(); // 保存历史记录
      } else if (buttonText == "√") {
        double num = double.parse(_output);
        double sqrtResult = math.sqrt(num);
        _output = sqrtResult.toString();
      } else if (buttonText == "%") {
        double num = double.parse(_output);
        double percentage = num / 100;
        _output = percentage.toString();
      } else if (buttonText == ".") {
        if (!_output.contains(".")) {
          _output += ".";
        }
      } else if (buttonText == "±") {
        double num = double.parse(_output);
        num *= -1;
        _output = num.toString();
      }else if (buttonText == "←") {
        // 处理删除逻辑
        if (_output.length > 1) {
          _output = _output.substring(0, _output.length - 1);
        } else {
          _output = "0";
        }
      } else if (buttonText == "x²") {
        // 处理平方逻辑
        double num = double.parse(_output);
        double squareResult = num * num;
        _output = squareResult.toString();
      } else if (buttonText == "㏒") {
        // 处理对数逻辑
        double num = double.parse(_output);
        double logResult = math.log(num);
        _output = logResult.toString();
      } else if (buttonText == "sin") {
        // 处理正弦逻辑
        double num = double.parse(_output);
        double sinResult = math.sin(num * math.pi / 180);
        _output = sinResult.toString();
      } else {
        if (_output == "0") {
          _output = buttonText;
        } else {
          _output = _output + buttonText;
        }
      }
    });
  }
  void _viewHistory() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => HistoryScreen(history: _history)),
    );
  }
  @override
  void initState() {
    super.initState();
    _loadHistory(); // Load history when the app launches
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('计算器'),  //标题显示为中文 "计算器"
        actions: [
          IconButton(
            icon: Icon(Icons.history),
            onPressed: _viewHistory, // Added view history button
          ),
          IconButton(
            icon: Icon(Icons.delete),
            onPressed: _clearHistory,
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: Container(
              padding: EdgeInsets.all(16),
              alignment: Alignment.centerRight,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    _displayText,
                    style: TextStyle(fontSize: 20),
                  ),
                  SizedBox(height: 12),
                  Text(
                    _output,
                    style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
            ),
          ),
          Divider(height: 1),
          Padding(
         padding: EdgeInsets.fromLTRB(8, 0, 8, 15),//计算器按键与底部保持 15 像素的距离,并将屏幕两边的按键与屏幕边缘保持 8 像素的距离
           // padding: EdgeInsets.only(bottom: 15),
    child:Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildButton("sin"),
                  _buildButton("x²"),
                  _buildButton("C"),
                  _buildButton("←"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildButton("√"),
                  _buildButton("%"),
                  _buildButton("㏒"),
                  _buildButton("÷"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly, // 设置主轴对齐方式为均匀分布
                children: [
                  _buildButton("7"),
                  _buildButton("8"),
                  _buildButton("9"),
                  _buildButton("x"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly, // 设置主轴对齐方式为均匀分布
                children: [
                  _buildButton("4"),
                  _buildButton("5"),
                  _buildButton("6"),
                  _buildButton("-"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly, // 设置主轴对齐方式为均匀分布
                children: [
                  _buildButton("1"),
                  _buildButton("2"),
                  _buildButton("3"),
                  _buildButton("+"),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly, // 设置主轴对齐方式为均匀分布
                children: [
                  _buildButton("±"),
                  _buildButton("0"),
                  _buildButton("."),
                  _buildButton("="),
                ],
              ),
            ],
          ),
          ),
        ],
      ),
    );
  }

  Widget _buildButton(String buttonText) {
    return Expanded(

        child: Container(
        padding: EdgeInsets.all(5),
      child: ElevatedButton(
        onPressed: () => _buttonPressed(buttonText),
        style: ElevatedButton.styleFrom(
         padding: EdgeInsets.all(25),

        ),
        child: Text(
          buttonText,
          style: TextStyle(fontSize: 25),
        ),
      ),
        ),
    );
  }
}

class HistoryScreen extends StatelessWidget {
  final List<String> history;

  HistoryScreen({required this.history});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('History'),
      ),
      body: ListView.builder(
        itemCount: history.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(history[index]),
          );
        },
      ),
    );
  }
}

在这里插入图片描述

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜欢听风的人

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值