Menu
CoddyTech

Strings With Variables

Part of the Your First App section of Coddy's Flutter journey. Lesson 12 of 32.

To put a variable inside a string, write a dollar sign and its name:

String name = 'Ada';
Text('Hello, $name!')   // Hello, Ada!

This is called string interpolation. For more than a plain name, like a calculation or a property, wrap it in curly braces after the dollar sign:

Text('$name has ${name.length} letters')   // Ada has 3 letters

name.length is how many letters the string has. Without the braces, '$name.length' would show the name followed by .length.

challenge icon

Challenge

Easy

The app has a variable name. Make its two lines say, using the variable:

  • Hello, Grace!
  • Grace has 5 letters, with the number from name.length

The Column around them puts one line under the other. You will build your own in a later chapter.

Try it yourself

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    String name = 'Grace';
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('Hello!'),
              Text('Letters'),
            ],
          ),
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Your First App

Practice on your own: Online Flutter compiler