Flutter交易逻辑代码校验及计算结果在Text Widget中展示方法
代码校验与修复
你的代码存在几个核心逻辑错误:
- 资金处理逻辑错误:
money = money - money;会直接把现有资金清零,完全不符合买入场景的逻辑,买入只需要记录当前数值作为持仓成本,而非清空资金。 - 盈亏计算时机错误:买入时立刻取
newValue和boughtValue,两者数值完全一致,导致currentSitPercent永远为0,没有实际意义。 - 缺失卖出逻辑:没有实现点击“卖出”时计算返还金额的核心逻辑。
修复后的核心代码示例
// 记录买入时的随机数值,null表示未持仓 int? boughtPrice; int currentSitMoney = 0; int currentSitPercent = 0; // 初始资金,可根据需求调整 int money = 1000; // 随机数生成器 final Random random = Random(); // 当前随机数值(1-999) int currentRandomValue = random.nextInt(999) + 1; // 买入操作 void buyValue() { setState(() { // 避免重复买入 if (boughtPrice == null) { boughtPrice = currentRandomValue; // 若需要扣减买入成本,可在此添加逻辑,比如:money = money - 买入成本 } }); } // 卖出操作 void sellValue() { setState(() { if (boughtPrice != null) { // 计算盈亏百分比,取整 currentSitPercent = ((currentRandomValue - boughtPrice!) / boughtPrice! * 100).toInt(); // 计算卖出后返还的总金额 currentSitMoney = money + (money * currentSitPercent ~/ 100); // 卖出后更新资金并重置持仓状态 money = currentSitMoney; boughtPrice = null; } }); } // 实时更新当前盈亏(可选,随机数变化时自动计算) void updateProfit() { setState(() { if (boughtPrice != null) { currentSitPercent = ((currentRandomValue - boughtPrice!) / boughtPrice! * 100).toInt(); currentSitMoney = money + (money * currentSitPercent ~/ 100); } else { // 未持仓时重置显示 currentSitPercent = 0; currentSitMoney = money; } }); }
在Text Widget中显示结果
直接在Widget树中用Text组件绑定变量即可,示例代码:
Column( mainAxisAlignment: MainAxisAlignment.center, children: [ // 显示当前随机数值 Text("当前数值: $currentRandomValue", style: const TextStyle(fontSize: 18)), // 显示盈亏比例,正数加+号区分盈利 Text("盈亏比例: ${currentSitPercent > 0 ? "+$currentSitPercent%" : "$currentSitPercent%}", style: TextStyle( fontSize: 18, color: currentSitPercent > 0 ? Colors.green : currentSitPercent < 0 ? Colors.red : Colors.black )), // 显示当前金额/返还金额 Text("当前金额: $currentSitMoney", style: const TextStyle(fontSize: 18)), const SizedBox(height: 20), // 买入按钮 ElevatedButton( onPressed: buyValue, child: const Text("买入"), ), const SizedBox(height: 10), // 卖出按钮 ElevatedButton( onPressed: sellValue, child: const Text("卖出"), ), const SizedBox(height: 10), // 刷新随机数值按钮 ElevatedButton( onPressed: () { setState(() { currentRandomValue = random.nextInt(999) + 1; updateProfit(); }); }, child: const Text("刷新数值"), ), ], )
关键说明
- 买入仅记录当前随机数作为持仓成本,资金扣减逻辑可根据你的业务需求自行调整。
- 卖出时基于当前随机数和买入价计算盈亏,最终更新返还的总资金。
- 可选的
updateProfit方法能在随机数变化时自动计算当前盈亏,提升界面交互性。
内容的提问来源于stack exchange,提问作者yarinmats
相关产品推荐
相关产品推荐

