Printing int value in Text widget flutter

Viewed 5291

How do we print the int value in Text widget? I tried using '$num' but it just come out as instance of num.

This is what i tried so far

Text(
   '$widget.count'+'. ',
    style: TextStyle(
    fontFamily: 'sansPro',
    fontSize: 15,
    color: Colors.black,
    fontWeight: FontWeight.bold,
      ),
    ),
2 Answers

In your specific case you need to wrap the data with {}, So update the code to the following,

Text(
   '${widget.count}''. ',
    //...
);

And for more details:

To "print" or "render" a num value that is an int or a double in dart you can use the .toString() method on the variable. You can also use "String Interpolation" that is to evaluate a variable or an expression in a String.

For Example to create a Text widget that renders the a variable X:

Text(x.toString());

And using String Interpolation, you can use:

Text("$x");

If the variable needs to be evaluated as a part of an expression, That is if the vailable is part of an Object or you want to apply an operation before evaluating the final value, then the expression needs to be wrapped within {}, the code for that would be

Text("${x * 100}");

Text widget accept only data in a String format so you can get value in a int or double format and while displaying it convert it into String format. Consider a code snippet like a below:

intValueCount.toString()
Related