I'm trying to change the color of a text field that is created and added to a map through a function called addFields() but with no success.. Whereas when I add the Text Field directly without a function or a map the color changes as expected. I don't know what I'm doing wrong since I'm new to Flutter and programing in general.. If anyone can help I'd be very appreciated. thanks..
here is my code:
// ignore_for_file: avoid_print
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
//
@override
void initState() {
addFields();
super.initState();
}
final Map<int, TextField> fields = {};
//
Color problemColor = const Color(0xff4caf50);
Color noProblemColor = const Color(0xff4caf50);
//
void addFields() {
final newTextField = TextField(
decoration: InputDecoration(filled: true, fillColor: problemColor),
onChanged: ((val) {
setState(() {
problemColor = const Color(0xfff44336);
});
}),
);
fields[0] = newTextField;
}
@override
Widget build(BuildContext context) {
print('problemColor = $problemColor');
print('noProblemColor = $noProblemColor');
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
fields[0]!,
TextField(
decoration:
InputDecoration(filled: true, fillColor: noProblemColor),
onChanged: ((val) {
setState(() {
noProblemColor = const Color(0xfff44336);
});
}),
)
],
),
),
);
}
}