i am creating very easy app - user will get 4 texfields and he will put there numbers. Then i want to do some math on that numbers. How is it possible to save that inputs in variables which i could use wherever i want and in relevant moment?
For now i only created possibility to display it on this class where they were created:
my TextFields look like this (i have 4 textfields: e, f, g and h:
var e = '';
TextField(
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
onChanged: (newVal) {
e = newVal;},),
And this is button - when i click it i can see inputs
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text('You wrote $d $e $f $g'),
);
},
);
But how to save that inputs to variables outside this class?
CodePudding user response:
You can save the value from onChanged
to a state management solution like StatefulWidget
or Providers
and so on.
TextField(
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
onChanged: (newVal) {
if(newVal != null){
context.read<SignUpBloc>().add(SignUpEvent.mobileChanged(mobile: newVal));
}
},),
This is how we do it in Bloc
. You can do the same in any other state management solution or even store it locally in SharedPreferences
as well.
CodePudding user response:
First you need to create a TextEditingController inside you class for each field you want to change:
class _MyClassWithDataState extends State<MyClassWithData> {
TextEditingController textController1 = TextEditingController();
TextEditingController textController2 = TextEditingController();
TextEditingController textController3 = TextEditingController();
TextEditingController textController4 = TextEditingController();
}
and define on the other class the data you will need:
class ClassWithReceivedData extends StatefulWidget {
const ClassWithReceivedData({
Key? key,
required this.text1,
required this.text2,
required this.text3,
required this.text4,
}) : super(key: key);
final TextEditingController text1;
final TextEditingController text2;
final TextEditingController text3;
final TextEditingController text4;
@override
State<ClassWithReceivedData> createState() =>
_ClassWithReceivedDataState();
}
then when you navigate to other page you simple pass:
Navigator.push(context, new MaterialPageRoute(builder: (context) => new
ClassWithReceivedData(text1: textController1, text2: textController2,
text3: textController3, text4: textController4);
but if you really need to retrieve data on multiple classes i suggest to create a Controller or a Store class for the data you need an then use an state managment like Provider, Get, Mobx, etc..., to retrieve data whatever you want.