我一直在尝试在文本小部件上显示双变量,但我不断收到此错误消息:
错误:方法调用不是常量表达式。 bid.toString()
我尝试了 toString() 甚至使用了 $bid 但它仍然不起作用。在文本小部件上显示 Int 或 Double 的最佳方式是什么
我无法在文本小部件上显示 double 或 int 的原因可能是什么? 这是我的代码:
import 'dart:math';
import 'package:flutter/material.dart';
class BuyXSO extends StatefulWidget {
const BuyXSO({super.key});
@override
State<BuyXSO> createState() => _BuyXSOState();
}
class _BuyXSOState extends State<BuyXSO> {
double bid = roundNumber(1.324, 2);
double offer = roundNumber((2.75, 2);
double roundNumber(double value, int places) {
num val = pow(10.0, places);
return ((value * val).round().toDouble() / val);
}
@override
Widget build(BuildContext context) {
return Column(
children: [
//XSO Ticker
Padding(
padding: const EdgeInsets.all(15.0),
child: Container(
padding: EdgeInsets.all(15.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
border: Border.all(color: const Color.fromARGB(255, 218, 216, 216)),
),
child: const SizedBox(
height: 50,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Text('XSocial',
style: TextStyle(fontSize: 18),
),
Text(' XSO',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold,),
),
],
),
VerticalDivider(
color: Color.fromARGB(255, 218, 216, 216),
thickness: 1,
),
Column(
children: [
Text('BID',
style: TextStyle(fontSize: 12, color: Colors.black54),
),
Text(
bid.toString(),
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: const Color.fromARGB(255, 2, 160, 68),
),
),
],
),
VerticalDivider(
color: Color.fromARGB(255, 218, 216, 216),
thickness: 1,
),
Column(
children: [
Text('OFFER',
style: TextStyle(fontSize: 12, color: Colors.black54),
),
Text(
offer.toString(),
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: const Color.fromARGB(255, 2, 160, 68),
),
),
],
),
],
),
),
),
),
],
);
}
}
我认为有两个问题。您必须先声明 roundNumber 方法,然后才能使用它,因此您需要将其使用转移到 _BuyXSOState.build 覆盖中:
...
class _BuyXSOState extends State<BuyXSO> {
double roundNumber(double value, int places) {
num val = pow(10.0, places);
return ((value * val).round().toDouble() / val);
}
@override
Widget build(BuildContext context) {
double bid = roundNumber(1.324, 2),
offer = roundNumber(2.75,2);
return Column(
children: [
...
然后您可能需要查看此答案以将动态内容添加到列中,因为您似乎无法像您尝试的那样动态声明文本:How to add the widgetsdynamic to columns in Flutter ?
这有帮助吗?