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]),
          );
        },
      ),
    );
  }
}
相关推荐
racerun1 分钟前
Vue vuex.store mapState
前端·javascript·vue.js
yep吖5 分钟前
Datawhale-AI冬令营二期
开发语言·javascript·ecmascript
胡西风_foxww11 分钟前
【ES6复习笔记】箭头函数(5)
javascript·笔记·es6·函数·箭头·箭头函数
残花月伴1 小时前
axios
javascript
van叶~2 小时前
仓颉语言实战——2.名字、作用域、变量、修饰符
android·java·javascript·仓颉
泯泷2 小时前
JS代码混淆器:JavaScript obfuscator 让你的代码看起来让人痛苦
开发语言·javascript·ecmascript
IT管理圈2 小时前
50个JAVA常见代码大全:学完这篇从Java小白到架构师
java·windows·python
高兴蛋炒饭9 小时前
RouYi-Vue框架,环境搭建以及使用
前端·javascript·vue.js
ᥬ 小月亮10 小时前
Vue中接入萤石等直播视频(更新中ing)
前端·javascript·vue.js
夜斗(dou)10 小时前
node.js文件压缩包解析,反馈解析进度,解析后的文件字节正常
开发语言·javascript·node.js