Skip to main content

Flutter Call Variable in Text Widget as String Example

Hello friends, Our today's tutorial is about defining and calling custom variables directly to Text widget in flutter. Because we cannot always call static text. Sometimes we have to update Text using state or sometimes we have to call data from a object with key if we use JSON object in our data. Flutter does support calling variable in text widget as string text in various format with various data types. If we declare variable into Double or Integer data type then at the time of calling it will automatically convert the text into string.

Flutter Call Variable in Text Widget as String Example:

1. Defining String variable and calling the variable in Text using $ symbol.
  final String demoText = 'world!';

     Text(
          'Hello $demoText',
          style: const TextStyle(fontSize: 30),
        ),
2. Defining Static Const String variable and calling into Text. Here we do not need to use $ symbol because it reflects as Static string.
static const String demoStaticText = 'hello guys...';

     const Text(
          demoStaticText,
          style: TextStyle(
            fontSize: 30,
          ),
        ),
3. Defining Double variable and calling the value in Text using $ symbol.
final double doubleValue = 55.55;

    Text(
          'Double Value = $doubleValue',
          style: const TextStyle(
            fontSize: 30,
          ),
        ),
4. Creating Integer variable and calling the Int variable in Text using $ symbol.
  final int integerValue = 20;

        Text(
          'Integer Value = $integerValue',
          style: const TextStyle(
            fontSize: 30,
          ),
        ),
5. Complete source code for main.dart file:
import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  final String demoText = 'world!';
  static const String demoStaticText = 'hello guys...';
  final double doubleValue = 55.55;
  final int integerValue = 20;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: SafeArea(
              child: Center(
                  child: Column(children: [
        Text(
          'Hello $demoText',
          style: const TextStyle(fontSize: 30),
        ),
        const Text(
          demoStaticText,
          style: TextStyle(
            fontSize: 30,
          ),
        ),
        Text(
          'Double Value = $doubleValue',
          style: const TextStyle(
            fontSize: 30,
          ),
        ),
        Text(
          'Integer Value = $integerValue',
          style: const TextStyle(
            fontSize: 30,
          ),
        ),
      ])))),
    );
  }
}
Screenshot:
Flutter Call Variable in Text Widget as String Example

Comments