skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. You can use for special character.

    '$fooXXX$'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search