This is the program I have running:
- I have an app that is a single page.
- The page’s widgets are defined in separate files.
- I have data that comes from the serial port and data that is entered in a form widget.
- The button widget that calls the function to write the data to the file is in a separate widget from the form widget (for layout reasons and because I’m taking data from the form and the serial buffer).
- I’m using Riverpod to manage the serial data.
-the Serial data gets passed as a List<List> tofile write function when the button is pressed.
onPressed: () {
if (ref.watch(serDataProvider).isNotEmpty) {
// Write the data to a file
writeFile(ref.watch(serDataProvider));
}
},
-the write file function is just formatting the data as a .csv file so that it comes up in Excel nicely, and in a way that I can easily select the data create a chart and copy/paste readymade titles.
-With hardcoded form data in the file write function, everything works perfectly.
I’m trying to get the form data to the function when the button is pressed.
- I already have the form created and their contents go into controllers. They work, I can print out the values locally in the form widget.
I tried creating a provider for a data class that holds it:
class Data {
late String? temperature;
late String? humidity;
Data(
this.temperature,
this.humidity,
factory Data.initial() {
return Data();
}
}
@riverpod
class FormData extends _$FormData {
@override
Data build() {
return Data.initial();
}
}
I added the data to the provider in the TextFields
like this:
onChanged: (text) {
ref.read(formDataProvider).temperature = text;
});
I added the form data to the button (function receiving FormData
as the datatype) like this:
onPressed: () {
if (ref.watch(serDataProvider).isNotEmpty) {
// Write the data to a file
writeFile(ref.watch(formDataProvider), ref.watch(serDataProvider));
}
},
In the function, I
void writeFile(Data formData, List<List> listOfSamples) async {
.
. // other code
.
sink.write(‘Temperature: ${formData.temperature}n’);
.
. // other code
.
}
It wasn’t throwing any errors, but I ended up with null
(as text) in the file wherever stuff from the form was printed.
I tried passing the form data to the provider in functions a number of different ways, and got the same result.
Looking at the Riverpod page, it states:
*They are not meant to be used for local widget state, such as for:
-storing form state
-currently selected item
-animations
–generally everything that Flutter deals with a “controller” (e.g. TextEditingController)*
So, it appears that my approach is maybe not a good one. If that is the case, what are some good ways of getting the form data to my function?