在Flutter中实现数学计算有多种方式:
1. 使用Dart内置数学库
import 'dart:math';
void main() {
// 基本运算
double result = 5 + 3 * 2; // 11.0
// 使用数学函数
double sqrtValue = sqrt(16); // 4.0
double powerValue = pow(2, 3).toDouble(); // 8.0
double sinValue = sin(pi / 2); // 1.0
print('结果: $result, 平方根: $sqrtValue, 幂运算: $powerValue, 正弦: $sinValue');
}
2. 在Flutter Widget中使用
import 'package:flutter/material.dart';
import 'dart:math';
class CalculatorWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
double area = pi * pow(5, 2); // 计算圆面积
return Scaffold(
appBar: AppBar(title: Text('数学计算示例')),
body: Center(
child: Text(
'半径为5的圆面积: ${area.toStringAsFixed(2)}',
style: TextStyle(fontSize: 20),
),
),
);
}
}
3. 复杂数学计算
import 'dart:math';
class MathCalculator {
// 计算两点间距离
static double distanceBetweenPoints(
double x1, double y1, double x2, double y2) {
return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
}
// 阶乘计算
static int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
// 解一元二次方程
static List<double> solveQuadratic(double a, double b, double c) {
double discriminant = b * b - 4 * a * c;
if (discriminant < 0) return [];
if (discriminant == 0) return [-b / (2 * a)];
double sqrtDiscriminant = sqrt(discriminant);
return [
(-b + sqrtDiscriminant) / (2 * a),
(-b - sqrtDiscriminant) / (2 * a)
];
}
}
4. 使用外部数学库
在pubspec.yaml中添加:
dependencies:
decimal: ^2.3.0
使用示例:
import 'package:decimal/decimal.dart';
void decimalCalculation() {
Decimal d1 = Decimal.parse('0.1');
Decimal d2 = Decimal.parse('0.2');
Decimal result = d1 + d2; // 精确的0.3,避免浮点数精度问题
}
主要数学函数
sqrt() - 平方根
pow() - 幂运算
sin(), cos(), tan() - 三角函数
log(), exp() - 对数和指数
max(), min() - 最大最小值
pi, e - 数学常量
Flutter的数学计算基于Dart语言,具备完整的数学运算能力,可以满足大多数应用场景的需求。