-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
providers: introduce package, add balance provider
- Loading branch information
Showing
3 changed files
with
68 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import 'dart:async'; | ||
|
||
import 'package:flutter/material.dart'; | ||
import 'package:get_it/get_it.dart'; | ||
import 'package:sidesail/rpc/rpc.dart'; | ||
|
||
class BalanceProvider extends ChangeNotifier { | ||
RPC get _rpc => GetIt.I.get<RPC>(); | ||
|
||
// because the class extends ChangeNotifier, any subscribers | ||
// to this class will be notified of changes to this | ||
// variable. | ||
double balance = 0; | ||
bool initialized = false; | ||
|
||
// used for polling | ||
late Timer _timer; | ||
|
||
BalanceProvider() { | ||
fetch(); | ||
_startPolling(); | ||
} | ||
|
||
// call this function from anywhere to refresh the balance | ||
Future<void> fetch() async { | ||
balance = await _rpc.getBalance(); | ||
// TODO: Handle error? | ||
|
||
initialized = true; | ||
notifyListeners(); | ||
} | ||
|
||
void _startPolling() { | ||
_timer = Timer.periodic(const Duration(seconds: 5), (timer) async { | ||
await fetch(); | ||
notifyListeners(); | ||
}); | ||
} | ||
|
||
@override | ||
void dispose() { | ||
super.dispose(); | ||
// Cancel timer when provider is disposed (never?) | ||
_timer.cancel(); | ||
} | ||
} |