where to load model from file in flutter apps? - flutter

Suppose I store my data in a dedicated repo class like so:
class UrlEntry {
final String url;
final String title;
UrlEntry({#required this.url, this.title});
}
class UrlRepository with ChangeNotifier {
List<UrlEntry> urlEntries = new List<UrlEntry>();
// Returns the urls as a separate list. Modifyable, but doesnt change state.
List<UrlEntry> getUrls() => new List<UrlEntry>.from(urlEntries);
add(UrlEntry url) {
this.urlEntries.add(url);
print(
"url entry ${url.url} added. Now having ${urlEntries.length} entries ");
notifyListeners();
}
removeByUrl(String url) {
var beforeCount = this.urlEntries.length;
this.urlEntries.removeWhere((entry) => entry.url == url);
var afterCount = this.urlEntries.length;
if (beforeCount != afterCount) notifyListeners();
print("removed: ${beforeCount != afterCount}");
}
save() async {
final storageFile = await composeStorageFile();
print("storage file is '${storageFile.path}");
if (await storageFile.exists()) {
print("deleting existing file");
await storageFile.delete();
}
if (urlEntries == null || urlEntries.length < 1) {
print("no entries to save");
return false;
}
print(
"saving ${urlEntries.length} url entries to file $storageFile} ...");
for (var entry in urlEntries) {
await storageFile.writeAsString('${entry.url} ${entry.title}',
mode: FileMode.append);
}
}
Future<File> composeStorageFile() async {
Directory storageDir = await getApplicationDocumentsDirectory();
return File('${storageDir.path}/url_collection.lst');
}
void dispose() async {
super.dispose();
print("disposing ...");
urlEntries.clear();
this.urlEntries = null;
}
load() async {
final storageFile = await composeStorageFile();
if (!await storageFile.exists()) {
print("storage file ${storageFile.path} not existing - not loading");
return false;
}
print("loading file ${storageFile.path}");
urlEntries = List <UrlEntry> () ;
final fileLines = storageFile.readAsLinesSync() ;
for (var line in fileLines) {
var separatorIndex = line.indexOf(' ') ;
final url = line.substring(0, separatorIndex) ;
var title = line.substring(separatorIndex+1) ;
if (title == 'null') title = null ;
urlEntries.add(new UrlEntry(url: url, title: title)) ;
}
notifyListeners() ;
}
}
Above code has several issues I unfortunately donnot know how to circumvent:
most of the methods of UrlRepository are async. This is because of getApplicationDocumentsDirectory() being async. I think former is an absolute flaw but introducing semaphores here to create an artificial bottleneck would pollute the code, so I still stick to async; but call me old-fashioned - I dont like the idea having save and load operations being theoretically able to overlap each other. I mean, with getApplicationDocumentsDirectory, we're talking about a simple configurational detail that will not need much computational power to compute, nor to store, nor will it change that often and it pollutes the code with otherwise unnessecary stuff. So, Is there another way to get the results of getApplicationDocumentsDirectory() without await / async / then ?
If this is not the case - where should I put the call to save()? My first idea was to save data not every model change, but instead at the latest possible executional place, which is one of the dispose-related methods, like so:
class MyAppState extends State<MyApp> {
UrlRepository urlRepository;
...
#override
void deactivate() async {
await urlRepository.save() ;
super.deactivate();
}
Unfortunately this results in urlRepository.save() being executed only the half, no matter whether I call it in a unit test, on a avd or on a real device. Right in the middle its terminated - I checked that with printouts. I think this is because, being forced again to make a completely unrelated method async (here deactivate()), I have to accept that execution is not granted to terminate at the return command, but earlier (?). I tried to put the call to MyState.dispose() as well as to urlRepository.dispose() with the same result except I cannot make the dispose methods async and hence just call save() async and hope everything has been saved before super.dispose() kicks in,...
I thought it natural to load the repositotry state inside of initState(), but I want to make sure that either the load has completed before creating widgets (ie calling the builder), or will be loaded after all widgets have already been in place so the model change will trigger rebuild. Since load() has to be async for known reasons and initState is not, I cannot assure even one of above cases and stick with urlRepository.load() and hope the best. So, where to put the call to urlRepository.load() ?

First: You have to use async/await methods because you don't know what the user's device may be doing while running your application, so even though the device might be performing a process that "doesn't need much power computational" that process may take a little longer than expected.
Second: Do not trust in deactivate() and dispose() functions, the user could kill your app and it would never do the save process. I'm not really sure how to automate this process. I suggest you do it manually somewhere in your code.
Third: Don't use initState() to load your data, you should use a FutureBuilder in which the future parameter is your urlRepository.load() function, while its loading you can show a CircularProgressIndicator() and if it has data you show your widget.
Example:
#override
Widget build() {
return FutureBuilder(
future: urlRepository.load() // without await keyword
builder: (context, snapshot) {
if(!snapshot.hasData)
return CircularProgressIndicator();
return YourWidget(); // if snapshot.hasData is true the process has finished
}
);
}
Psdt: It might be useful if urlRepository.load() would return something like a bool. Doing this you could show a widget if snapshot.data is true or another widget if snapshot.data is false.

Related

getting the return value of Future Function in Flutter without Stateless/Stateful Widget

I just want to return the value of each condition and use it as the value of the function.
Here is my code for it.
var getStuff = chechIfExisting();
chechIfExisting() async {
var isExisting = await FirebaseFirestore.instance
.collection('merchants')
.doc(userUid)
.get();
if (isExisting.exists) {
return 'exists';
}
if (!isExisting.exists) {
return 'nope';
} else {
return 'error';
}
}
and I am not using any Stateless and Stateful Widget since this file contains only the widgets such as appbar/mydrawer. I wanted to use the 'getStuff' variable in a if statement under the myDrawer Widget, since I want to dynamically check if the the data that I am fetching is existing or not.
myDrawer(BuildContext context) {
print('getStuff');
// only prints 'Instance of 'Future<String>' and does not return the value.
}
I want to be able to use the 'getStuff' variable as
myDrawer(BuildContext context) {
if(getStuff == 'exists'){
// code here
}
Any helps/ideas on how to solve this are appreciated!
with this line:
var getStuff = chechIfExisting();
You're not waiting for the method to finishes executing, since it's a Future, not using either await/async or then to resolve values after the Future finishes will get you that getStuff() is a type of Instance of 'Future<String>, before the running of the myDrawer function, you need either to:
var getStuff = await chechIfExisting(); // inside an async method
or:
chechIfExisting().then((resolvedValue) {
getStuff = resolvedValue;
});
then you can run the myDrawer method and get it working fine

How to get the 'bool' value from a Future<bool> into a field variable, for later use

I am using flutter_blue package for using the Bluetooth service. I want to check whether the device has Bluetooth capabilities. The method isAvailable seems to do it. However, it returns a Future<bool>, which I am tryting to get into a variable as follows:
import 'package:flutter_blue/flutter_blue.dart';
class BT_Base {
final FlutterBlue _fb = FlutterBlue.instance;
bool BTAvailable = true; // as a default placeholder
BT_Base () {
BTAvailable = _fixAvail();
}
_fixAvail () async {
return await _fb.isAvailable;
}
...
I try to get the future value from it and store into BTAvailable. Later on, I use the fixed BTAvailable field to get the appropriate Widget to be passed onto as follows:
class BTDevicePrompt extends StatelessWidget {
#override
Widget build(BuildContext context) {
BT_Base bt = BT_Base();
var btDeviceRes = bt.scan();
if(!bt.BTAvailable) return Text('Bluetooth unavailable on device...');
else if (btDeviceRes.isEmpty) return Text('No Bluetooth devices in range...');
else {
return CupertinoActionSheet(
actions: [
...
],
)
}
}
}
But I keep getting the error type 'Future<dynamic>' is not a subtype of type 'bool' at runtime. How can I use the Future properly in this situation? It is alright if the whole process just halts and waits for this part as well.
I have gone through a lot of solutions but I am not able to piece it together.
Any method marked async always returns a Future of some kind. You can give it an explicit return type like Future<bool> function() async { ... }, or if you leave it out it will infer Future<dynamic>.
In short, you can't get a bool from a Future<bool> outside of an async function (there are technically ways but almost certainly not what you want in Flutter).
This makes sense, since the whole point of a Future<bool> is that it's going to be a bool in the future. If there was some process to convert from a Future<bool> to a bool, what should it do if the future has not yet completed? Perhaps it should wait until it has completed. In that case, you're just describing the await keyword.
If, however, you want to use a Future in your UI in a Flutter application, you have a few options.
The simplest for your case will be to move it into initState():
class BTDevicePrompt extends StatefulWidget {
// stateful widget boilerplate
}
class BTDevicePromptState extends State<BTDevicePrompt> {
bool isAvailable = false;
#override
void initState() {
super.initState();
checkAvailable(); // use a helper method because initState() cannot be async
}
Future<void> checkAvailable() async {
// call an async function and wait for it to complete
bool result = await checkIfBluetoothAvailable();
setState(() => bluetoothAvailable = result); // set the local variable
}
#override
Widget build(BuildContext context) {
if (bluetoothAvailable) return Text('bluetooth available');
else return Text('bluetooth not available');
}
}

Flutter/Dart : How to wait for asynchronous task before app starts?

I am working on a dart application where I want to fetch the data present in cache (SharedPreferences) and then show it on UI (home screen) of the app.
Problem : Since SharedPreferences is an await call, my home page loads, tries to read the data and app crashes because data fetch has not yet happened from SharedPreferences, and app loads before that.
How can I not start the app until cache read from SharedPreferences is done?
This is required because I have to display data from SharedPreferences on home page of the app.
Various view files of my project call static function : MyService.getValue(key) which crashes as cacheResponseJson has not populated yet. I want to wait for SharedPreferences to complete before my app starts.
Class MyService {
String _cacheString;
static Map < String, dynamic > cacheResponseJson;
MyService() {
asyncInit();
}
Future < void > asyncInit() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
_cacheString = sharedPreferences.getString(“ConfigCache”);
cacheResponseJson = jsonDecode(ecsCacheString);
}
static String getValue(String key) {
return cacheResponseJson[key];
}
}
void main() {
MyService s = MyService();
}
Any help would be highly appreciated!
You can run code in your main() method, before the call to runApp() that kicks off your application.
For example:
void main() async {
WidgetsFlutterBinding.ensureInitialized(); // makes sure plugins are initialized
final sharedPreferences = MySharedPreferencesService(); // however you create your service
final config = await sharedPreferences.get('config');
runApp(MyApp(config: config));
}
Can you try wrapping the function asyncInit() in initstate then in the function then setstate the values
_cacheString = sharedPreferences.getString(“ConfigCache”);
cacheResponseJson = jsonDecode(ecsCacheString);
I hope it works.
avoid using initialization etc outside the runApp() function, you can create a singleton
class MyService{
MyService._oneTime();
static final _instance = MyService._oneTime();
factory MyService(){
return _instance;
}
Future <bool> asyncInit() async {
//do stuff
return true;
}
}
and incorporate that in the UI like this
runApp(
FutureBuilder(
future: MyService().asyncInit(),
builder: (_,snap){
if(snap.hasData){
//here you can use the MyService singleton and its members
return MaterialApp();
}
return CircularProgressIndicator();
},
)
);
if you take this approach you can do any UI related feedback for the user while the data loads

How to wait on getter in flutter?

Below is the code of a provider class. Whenever the app starts i want to get the forms which were saved in the shared preferences. However it is taking sometime to load the from sharedpreferences. So When i access the forms for the first time it is initially empty, im getting an empty list. Is there anyway to delay the getter until it has the objects of form model.
class FormProvider with ChangeNotifier {
FormProvider() {
loadformPreferences();
}
List<FormModel> _forms = [];
List<FormModel> get forms => _forms;
Future<void> saveForm(FormModel form) async {
_forms.add(form);
await saveformPreferences();
notifyListeners();
}
Future<void> saveformPreferences() async {
List<String> myforms = _forms.map((f) => json.encode(f.toJson())).toList();
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setStringList('forms', myforms);
}
Future<void> loadformPreferences() async {
// WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
var result = prefs.getStringList('forms');
if (result != null) {
_forms = result.map((f) => FormModel.fromJson(json.decode(f))).toList();
}
}
}
In Flutter, all actions related to building the UI must not be asynchronous (or expensive) in order to main a high frame-rate.
Thus, even if you could hypothetically find a way to "wait" for the results from SharedPreferences, this would not be desirable, since whatever waiting was done would block the UI from making progress.
Thus, there are a couple approaches to this common problem:
Handle initial state explicitly in the UI
The simplest solution is to explicitly handle the case where the Provider has not yet fetched its data, by representing some sort of initial state in your Provider. One easy way to do this is to initialize _forms to null instead of []. Then in your Widget.build method, you could do something specific (like show a loading spinner) when the result is null:
Widget build(BuildContext context) {
final provider = Provider.of<FormProvider>(context);
if (provider.forms == null) {
return CircularProgressIndicator();
}
// Otherwise, Do something useful with provider.forms
}
Construct your provider with the resolved data
Let's say that you don't use the FormProvider until the user performs an action, like click a button, at which point you push a new view onto the navigator with the FormProvider.
If you wish to guarantee that the FormProvider will always be initialized with the SharedPreferences values, then you can delay the construction of the new view until SharedPreferences has finished:
class MyButton extends StatelessWidget {
Widget build(BuildContext context) {
return Button(onClick: () async {
final forms = await _fetchFormsFromSharedPrefs();
Navigator.push(context, MaterialPageView(builder: (context) =>
Provider(create: (_) => FormProvider(forms))));
});
}
}

Awaiting some results before dispatching an event with flutter_bloc library

I am trying to create a BLOC which depends on two other time based bloc and a non-time based bloc. What i mean with time based is, for example they are connecting a remote server so it takes time. It's working just like this:
Login (It's of course taking some time)
If login is successful
Do another process (This is something takes time also. It returns a future.)
After login and another process finishes, let the page know it.
My BLOC depends on these three:
final UserBloc _userBloc;
final AnotherBloc _anotherBloc;
final FinishBloc _finishBloc;
Inside the map event to state method I should dispatch relevant events. However i cannot await if they are finished.
_userBloc.dispatch(
Login(),
);
_anotherBloc.dispatch(
AnotherProcess(),
);
//LetThePageKnowIt should work after login and another process
_finishBloc.dispatch(
LetThePageKnowIt(),
);
Is there a clean way to await some others before dispatching something?
Right know I use a way that i don't like. In the main bloc's state which i connect other blocs in it, I have bools.
class CombinerState {
bool isLoginFinished = false;
bool isAnotherProcessFinished = false;
I am listening the time dependent blocs' states in constructor of main bloc. When they yield "i am finished" I just mark the bools "true".
MainBloc(
this._userBloc,
this._anotherBloc,
this._pageBloc,
); {
_userBloc.state.listen(
(state) {
if (state.status == Status.finished) {
dispatch(FinishLogin());
}
},
);
_anotherBloc.state.listen(
(state) {
if (state.status == AnotherStatus.finished) {
dispatch(FinishAnotherProcess());
}
},
);
}
and I dispatch another event for main bloc to check if all the bools are true after setting a bool to true.
else if (event is FinishAnotherProcess) {
newState.isAnotherProcessFinished = true;
yield newState;
dispatch(CheckIfReady());
}
If the bools are true, i dispatch LetThePageKnowIt()
else if (event is CheckIfReady) {
if (currentState.isAnotherProcessFinished == true &&
currentState.isLoginFinished == true) {
_pageBloc.dispatch(LetThePageKnowIt());
}
}
I am not satisfied with this code. I am looking a way to await other BLOCs send a state with "finished". After that I want to dispatch my LetThePageKnowIt()
#pskink 's suggestion solved my problem.
I have created two methods which return a future. Inside of them, I just await for my streams. Here is the example of login stream.
In map event to state, after the dispatches, I await an async method.
_userBloc.dispatch(
Login(),
);
_anotherBloc.dispatch(
AnotherProcess(),
);
await loginProcess();
await otherProcess();
_finishBloc.dispatch(
LetThePageKnowIt(),
);
Inside the method I just await for userbloc to finish its job and yields about it. Then return.
Future loginProcess() async {
await for (var result in _userBloc.state) {
if (result.status == Status.finished) {
return;
}
}
}