I have been trying to display a double variable on a Text Widget but I keep getting this error message:
Error: Method invocation is not a constant expression. bid.toString()
I tried the toString() and even using the $bid yet it still didn’t work. What is the best way to display Int or Double on Text widgets
What could be the reason I can’t display a double or int on a text widget?
Here is my code:
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),
),
),
],
),
],
),
),
),
),
],
);
}
}
2
Answers
I think there are two problems. You have to declare the roundNumber method before you can use it, so you need to move your use of it into the _BuyXSOState.build override:
Then you might want to review this answer to get the dynamic content into the column, because it doesn’t appear that you can dynamically declare the text like you’re trying to do: How to add the widgets dynamically to column in Flutter?
Does this help?
Two problems are found here.
Solution:
Here is the updated code:
#Output