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]),
);
},
),
);
}
}
flutter写的一个计算器并保存历史记录
喜欢听风的人2023-08-22 16:44
相关推荐
new出一个对象2 小时前
uniapp接入BMapGL百度地图你挚爱的强哥3 小时前
✅✅✅【Vue.js】sd.js基于jQuery Ajax最新原生完整版for凯哥API版本前端Hardy3 小时前
纯HTML&CSS实现3D旋转地球susu10830189113 小时前
vue3中父div设置display flex,2个子div重叠n***85944 小时前
嵌入式 UI 开发的开源项目推荐小袁搬码5 小时前
Windows中指定路径安装DockerDesktop小镇程序员6 小时前
vue2 src_Todolist全局总线事件版本疯狂的沙粒6 小时前
对 TypeScript 中函数如何更好的理解及使用?与 JavaScript 函数有哪些区别?瑞雨溪6 小时前
AJAX的基本使用力透键背6 小时前
display: none和visibility: hidden的区别