I want to create a multiscreen / multipart form wizard, with each screen containing:
- a question
- several different controls (text, radio-buttons etc.) which allow him to answer the question
I want to save the state of the answers to a remote server. For the radio buttons that's straight-forward (whenever the user changes it's value).
But what about text-fields? I don't want to update the server with every character change, but on the other hand I don'w want to lose data if the user exit the screen or the app closes / goes to background...
What would be the best approach to save data from text-fields? Can Flutter's Form help me with that?
CodePudding user response:
As the comment suggests you can use a debouncer for that. Creating a debouncer is pretty easy:
import 'package:flutter/foundation.dart';
import 'dart:async';
class Debouncer {
final int delay;
late VoidCallback action;
Timer? _timer;
Debouncer({required this.delay});
run(VoidCallback action) {
if (_timer != null) {
_timer?.cancel();
}
_timer = Timer(Duration(milliseconds: delay), action);
}
cancel() {
_timer?.cancel();
}
}
And to use it define it somewhere and then do:
yourDebouncer.run(() async {sendData(...)})
I suggest you send your data in the onchange method of your TextField
. This way your user data is saved and your server will certainly not be overwhelmed. Don't forget to cancel the Debouncer
in your dispose
method.
@override
void dispose() {
_d.cancel();
yourDebouncer.dispose();
}
You might want to have a look at this if you want more details on how to implement a Debouncer
.