1

I'm trying to set the value of a Text widget with a variable but I get the aforementioned error

Error dart (missing identifier) 

for the variable fooXXX where I add it to the Text widget

            Text(
              '$fooXXX$'
            ),

and I cannot work out what the error message actually means as I declared the variable at the top of the State class.

import 'package:flutter/material.dart';

void main() => runApp(const FooApp());

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Foo title',
      home: FooForm(),
    );
  }
}

class FooForm extends StatefulWidget {
  const FooForm({super.key});

  @override
  State<FooForm> createState() => FooFormState();
}

class FooFormState extends State<FooForm> {
  final fooXXXController = TextEditingController();
  String fooXXX = "This is the initial value";

  @override
  void initState() {
    super.initState();

    fooXXXController.addListener(handleStateChange);
  }

  @override
  void dispose() {
    fooXXXController.dispose();
    super.dispose();
  }

  void handleStateChange() {
    // do something
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('the bar'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Text(
              '$fooXXX$'
            ),
            TextField(
              controller: fooXXXController,
            ),
            FloatingActionButton(
              child: const Text("Generate"),
              onPressed: () {
                fooXXXController.text = "Button pressed";
              },
            )
          ],
        ),
      ),
    );
  }
}

2 Answers 2

2

Erase '$' after a string interpolation. '$' only goes before a variable interpolation.

Text('$fooXXX'),

Like that error will disappear :)

You could also use

Text(fooXXX)

Since you don't need to interpolate with only one String variable.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes that did it. But I swear I got the notion that it had to be "$variable_name$" from an example online which I don't have at hand now. It did seem strange considering it's a declared variable. tyvm for the answer.
0

You can use \ for special character.

'$fooXXX\$'

1 Comment

To update the UI, you need to call setState.

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.