5

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,
      ),
    ),
3
  • intValue.toString() Commented Jun 19, 2021 at 3:16
  • Can you provide more info? In all cases, using "$myInt" should be able to handle puting int values inside string. Can you add a bit more detail? Perhaps a few more line of code? Commented Jun 19, 2021 at 3:21
  • Consider if you want to use string interpolation and the value has in sub-class or widget, you should use {} i.e. '${widget.count}'+'. ', Commented Jun 19, 2021 at 3:24

3 Answers 3

12

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}");
Sign up to request clarification or add additional context in comments.

1 Comment

@alep if this answer helped you, consider marking it as the accepted answer. So we can help others with the same question on StackOverflow.
0

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()

Comments

0

it might be helpful for someone.

Issue:How to resolve "Invalid constant value." error - Flutter in VS Code

Let's suppose you want to show int value in Text e.g

import 'package:flutter/material.dart';

class ProductDetail extends StatelessWidget { final int productId;

const ProductDetail({super.key, required this.productId});

@override Widget build(BuildContext context) { return Container( child: Text("Id is ${productId} for Product Detail will go here"), ); } }

So Make sure no add any const before Text or any widget.

Thanks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.