I am getting an error in my Flutter app when trying to run it. The error message is "Invalid constant value." and it is pointing to this specific line (line 4 and 45) of code (obscureText).
The error seems to be related to the use of the const keyword in this line. I am trying to create a to hide and show password text, but the const keyword is causing an issue. Can someone please explain what this error means and how I can resolve it in my code?
import 'package:flutter/material.dart';
void main() {
runApp(const RunMyApp());
}
class RunMyApp extends StatefulWidget {
const RunMyApp({super.key});
@override
State<RunMyApp> createState() => _RunMyAppState();
}
class _RunMyAppState extends State<RunMyApp> {
bool passwordVisible = false;
final passwordController = TextEditingController();
bool obscureText = false;
@override
void initState() {
super.initState();
passwordVisible = true;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.green),
home: Scaffold(
appBar: AppBar(
title: const Text('Show or Hide Password in TextField'),
),
body: Container(
padding: const EdgeInsets.all(20.0),
child: TextFormField(
keyboardType: TextInputType.text,
controller: passwordController,
obscureText: !obscureText,
decoration: const InputDecoration(
hintText: 'Password',
prefixIcon: Icon(Icons.lock_open),
suffixIcon: IconButton(
icon: Icon(obscureText
? Icons.visibility
: Icons.visibility_off),
onPressed: () {
setState(() {
obscureText = !obscureText;
});
}),
),
validator: (value) {
if (value!.isEmpty) {
return 'Enter password';
}
return null;
},
),
)));
}
}
2
Answers
Try the following code:
You cant create const
InputDecoration
because theicon
andonPressed
is depended/changes on run time.Remove the const before
decoration: InputDecoration(