You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对TextEditingController中的值进行数学运算并在Text中展示?

Flutter 获取输入数值并计算显示的实现方案

完整实现代码

import 'package:flutter/material.dart';

class CalculatorScreen extends StatefulWidget {
  const CalculatorScreen({super.key});

  @override
  State<CalculatorScreen> createState() => _CalculatorScreenState();
}

class _CalculatorScreenState extends State<CalculatorScreen> {
  // 定义输入控制器
  late final TextEditingController _weightController = TextEditingController();
  late final TextEditingController _heightController = TextEditingController();
  
  // 存储计算结果
  double? _result;

  // 计算方法
  void _calculateResult() {
    // 将输入字符串转为数值,处理空或非数字情况
    final weight = double.tryParse(_weightController.text);
    final height = double.tryParse(_heightController.text);

    if (weight != null && height != null && height > 0) {
      // 这里以BMI计算为例:体重(kg) / (身高(m)的平方)
      setState(() {
        _result = weight / (height * height);
      });
    } else {
      // 输入不合法时清空结果
      setState(() {
        _result = null;
      });
    }
  }

  @override
  void dispose() {
    // 销毁控制器,避免内存泄漏
    _weightController.dispose();
    _heightController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('数值计算器')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // 体重输入框
            TextField(
              controller: _weightController,
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              decoration: const InputDecoration(
                labelText: '体重(kg)',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            // 身高输入框
            TextField(
              controller: _heightController,
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              decoration: const InputDecoration(
                labelText: '身高(m)',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 24),
            // 计算按钮
            ElevatedButton(
              onPressed: _calculateResult,
              child: const Text('计算'),
            ),
            const SizedBox(height: 24),
            // 显示结果
            Text(
              _result != null 
                  ? '计算结果: ${_result!.toStringAsFixed(2)}' 
                  : '请输入合法的数值',
              style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
          ],
        ),
      ),
    );
  }
}

关键部分说明

  • 控制器绑定:两个TextField分别绑定对应的TextEditingController,直接获取用户输入的文本内容。
  • 数值转换:用double.tryParse()把输入字符串转成数值,输入不合法时返回null,避免直接解析崩溃。
  • 状态更新:计算完成后调用setState()更新_result,触发UI重建让结果实时展示。
  • 内存管理:在dispose()方法中销毁控制器,防止内存泄漏。
  • 合法性校验:判断体重、身高不为空且身高大于0(避免除以0错误),不合法时提示用户修正输入。

你可以根据需求修改_calculateResult()里的运算逻辑,替换成其他数学公式。

内容的提问来源于stack exchange,提问作者ckot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:20:38