How do I use a method defined in another code section in the same file?
import 'package:flutter/material.dart';
import 'package:flutter_web3/flutter_web3.dart';
class MetamaskProvider extends ChangeNotifier {
static const operationChain = 4;
String currentAddress = '';
int currentChain = -1;
bool get isEnabled => ethereum != null;
bool get isInOperatingChain => currentChain == operationChain;
bool get isConnected => isEnabled && currentAddress.isNotEmpty;
Future<void> connect() async {
if (isEnabled) {
final accs = await ethereum!.requestAccount();
if (accs.isNotEmpty) currentAddress = accs.first;
currentChain = await ethereum!.getChainId();
notifyListeners();
}
void clear() {
currentAddress = '';
currentChain = -1;
}
}
init() {
if (isEnabled) {
ethereum!.onAccountsChanged((accounts) {
clear();
});
ethereum!.onAccountsChanged((accounts) {
clear();
});
}
}
}
error thrown when trying to use the "clear" method: The method 'clear' isn't defined for the type 'MetamaskProvider'.
You have to move the method clear() from connect() method to outside of it. Then, you will be able to access clear() inside init().
class MetamaskProvider extends ChangeNotifier {
static const operationChain = 4;
String currentAddress = '';
int currentChain = -1;
bool get isEnabled => ethereum != null;
bool get isInOperatingChain => currentChain == operationChain;
bool get isConnected => isEnabled && currentAddress.isNotEmpty;
void clear() {
currentAddress = '';
currentChain = -1;
}
Future<void> connect() async {
if (isEnabled) {
final accs = await ethereum!.requestAccount();
if (accs.isNotEmpty) currentAddress = accs.first;
currentChain = await ethereum!.getChainId();
notifyListeners();
}
}
init() {
if (isEnabled) {
ethereum!.onAccountsChanged((accounts) {
clear();
});
ethereum!.onAccountsChanged((accounts) {
clear();
});
}
}
}
Related
Future<bool> checkConnection() async {
var connectivityResult = await (Connectivity().checkConnectivity());
bool connOk = false;
if (connectivityResult == ConnectivityResult.mobile) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else if (connectivityResult == ConnectivityResult.wifi) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else if (connectivityResult == ConnectivityResult.ethernet) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else if (connectivityResult == ConnectivityResult.bluetooth) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else {
connOk = false;
}
return connOk;
}
Future<bool> checkConnectionWithUrl() async {
bool response = false;
while (true) {
var checkin = await client.get(Uri.https('www.google.com', '/'));
if (checkin.statusCode == 200) {
response = true;
break;
} else {
sleep(const Duration(milliseconds: 500));
}
}
return response;
}
Stream checkStream() async* {
dynamic result = false;
while (true) {
try {
result = await checkConnection();
} catch (error) {
result = false;
} finally {
yield result;
}
await Future.delayed(const Duration(seconds: 1));
}
}
I am making a app. And I want to learn multi threading in dart. The above function what it will do is it look for wifi state every second and update the Ui. But when I run the function it will drop frams in ui. So I what to run it in a diffrent thread. can i do it.
---My main goal ---
I want to run this function in a different thread how do I do it
couldnt find anything wrong with it
dependencies:
google_mobile_ads: ^1.1.0
Error:
MissingPluginException(No implementation found for method
MobileAds#initialize on channel plugins.flutter.io/google_mobile_ads)
at Object.throw_ [as throw] (http://localhost:58428/dart_sdk.js:5067:11)
at platform_channel.MethodChannel.new._invokeMethod (http://localhost:58428/packages/flutter/src/services/restoration.dart.lib.js:1560:21)
at _invokeMethod.next ()
at http://localhost:58428/dart_sdk.js:40571:33
at _RootZone.runUnary (http://localhost:58428/dart_sdk.js:40441:59)
at _FutureListener.thenAwait.handleValue (http://localhost:58428/dart_sdk.js:35363:29)
at handleValueCallback (http://localhost:58428/dart_sdk.js:35931:49)
at Function._propagateToListeners (http://localhost:58428/dart_sdk.js:35969:17)
at _Future.new.[_completeWithValue] (http://localhost:58428/dart_sdk.js:35817:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:58428/dart_sdk.js:35838:35)
at Object._microtaskLoop (http://localhost:58428/dart_sdk.js:40708:13)
at _startMicrotaskLoop (http://localhost:58428/dart_sdk.js:40714:13)
at http://localhost:58428/dart_sdk.js:36191:9
AdsManager :
class AdsManager {
static bool testMode = true;
late InterstitialAd? interstitialAd;
int numInterstitialLoadAttempts = 0;
static String get rewardedAdUnitId {
if (testMode == true) {
return RewardedAd.testAdUnitId;
} else if (Platform.isAndroid) {
return "ca-app-pub-1571703103044065/4157175333";
} else if (Platform.isIOS) {
return "ca-app-pub-1571703103044065/4157175811";
} else {
throw UnsupportedError("Unsupported platform");
}
}
static String get bannerAdUnitId {
if (testMode == true) {
return BannerAd.testAdUnitId;
} else if (Platform.isAndroid) {
return "ca-app-pub-1571703103044065/4157175333";
} else if (Platform.isIOS) {
return "ca-app-pub-1571703103044065/6858117501";
} else {
throw UnsupportedError("Unsupported platform");
}
}
static String get interstitialAdUnitId {
if (testMode == true) {
return InterstitialAd.testAdUnitId;
} else if (Platform.isAndroid) {
return "ca-app-pub-1571703103044065/4157175333";
} else if (Platform.isIOS) {
return "ca-app-pub-1571703103044065/2885703588";
} else {
throw UnsupportedError("Unsupported platform");
}
}
}
in page.dart
class _HomePageState extends State<HomePage> {
late RewardedAd _rewardedAd;
late InterstitialAd interstitialAd;
int numInterstitialLoadAttempts = 0;
bool isRewardedAdReady = false;
var _balance = 0;
//Banner Ad
late BannerAd _bannerAd;
bool _adIsLoaded = false;
#override
void initState() {
_initGoogleMobileAds();
_loadRewardedAd();
loadInterstitialAd();
//
_bannerAd = BannerAd(
adUnitId: AdsManager.bannerAdUnitId,
request: const AdRequest(),
size: AdSize.banner,
listener: BannerAdListener(
onAdLoaded: (ad) {
setState(() => _adIsLoaded = true);
},
onAdFailedToLoad: (ad, error) {
setState(() => _adIsLoaded = false);
},
));
_bannerAd.load();
//
super.initState();
}
#override
void dispose() {
super.dispose();
}
I have already got the geolocation with longitude and latitude using the geolocation plugin with getx but now I want to post the same longitude and latitude on API with already present in the backhand the model is yet to be created and even the provider is also yet to be done and I don't know how and the location API post should run in the background once with the application opens up.
API body:-
{
"longitude":"55.5852",
"latitude":"77.6532"
}
Controller code:-
class RootController extends GetxController {
var latitude = 'Getting Latitude..'.obs;
var longitude = 'Getting Longitude..'.obs;
var address = 'Getting Address..'.obs;
final currentIndex = 0.obs;
final notificationsCount = 0.obs;
final customPages = <CustomPage>[].obs;
NotificationRepository _notificationRepository;
CustomPageRepository _customPageRepository;
StreamSubscription<Position> streamSubscription;
RootController() {
_notificationRepository = new NotificationRepository();
_customPageRepository = new CustomPageRepository();
}
#override
void onInit() async {
await getCustomPages();
getNotificationsCount();
if (Get.arguments != null && Get.arguments is int) {
changePageInRoot(Get.arguments as int);
} else {
changePageInRoot(0);
}
super.onInit();
getLocation();
}
#override
void onReady(){
super.onReady();
}
#override
void onClose(){
streamSubscription.cancel();
}
getLocation() async{
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if(!serviceEnabled){
await Geolocator.openLocationSettings();
return Future.error('Location Services are disabled.');
}
permission = await Geolocator.checkPermission();
if(permission == LocationPermission.denied){
permission = await Geolocator.requestPermission();
if(permission == LocationPermission.denied){
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever){
return Future.error('Location permissions are permanently denied');
}
streamSubscription = Geolocator.getPositionStream().listen((Position position) {
latitude.value = 'Latitude:${position.latitude}';
longitude.value = 'Longitude:${position.latitude}';
getAddressFromLatLang(position);
print(latitude.value);
print(longitude.value);
});
}
Future<void> getAddressFromLatLang(Position position)async{
List<Placemark> placemark = await
placemarkFromCoordinates(position.latitude,position.longitude);
Placemark place = placemark[0];
address.value = 'address:${place.locality},${place.country}';
}
List<Widget> pages = [
HomeView(),
// EServicesView2(),
ReviewsView(),
MessagesView(),
AccountView(),
];
Widget get currentPage => pages[currentIndex.value];
/**
* change page in route
* */
void changePageInRoot(int _index) {
currentIndex.value = _index;
}
void changePageOutRoot(int _index) {
currentIndex.value = _index;
Get.offNamedUntil(Routes.ROOT, (Route route) {
if (route.settings.name == Routes.ROOT) {
return true;
}
return false;
}, arguments: _index);
}
Future<void> changePage(int _index) async {
if (Get.currentRoute == Routes.ROOT) {
changePageInRoot(_index);
} else {
changePageOutRoot(_index);
}
await refreshPage(_index);
}
Future<void> refreshPage(int _index) async {
switch (_index) {
case 0:
{
await Get.find<HomeController>().refreshHome();
break;
}
case 2:
{
await Get.find<MessagesController>().refreshMessages();
break;
}
}
}
void getNotificationsCount() async {
notificationsCount.value = await _notificationRepository.getCount();
}
Future<void> getCustomPages() async {
customPages.assignAll(await _customPageRepository.all());
}
}
what else should I do?
I want to update my Shared preference so that each time I update my Provider the updated List automatically gets stored in my shared preference. Here is my code.
class AlarmState extends ChangeNotifier {
var hour = 0;
var min = 0;
Set<Weekday> activeDays = Set();
bool alarmRing = false;
bool vibrate = false;
bool snooze = false;
List<AlarmObject> alarmList = [];
void update({
int? hour,
int? min,
Set<Weekday>? activeDays,
bool? alarmRing,
bool? vibrate,
bool? snooze,
List<AlarmObject>? alarmList,
}) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
this.hour = hour ?? this.hour;
this.min = min ?? this.min;
this.activeDays = activeDays ?? this.activeDays;
this.alarmRing = alarmRing ?? this.alarmRing;
this.vibrate = vibrate ?? this.vibrate;
this.snooze = snooze ?? this.snooze;
this.alarmList = alarmList ?? this.alarmList;
if (alarmList == null) {
return;
}
else{
preferences.setStringList("alarm_list",
alarmList.map((e) => jsonEncode(AlarmObject.toMap(e))).toList());
}
notifyListeners();
}
}
I am using the audioplayers plugin in my code.
I can play audio but I cannot stop/pause audio. Following is a function that I use to play/stop the audio.
Future<void> onPlay({#required filepath, #required index}) async {
AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);
if (!_isPlaying) {
int result = await audioPlayer.play(filepath, isLocal: true);
if (result == 1) {
setState(() {
_isPlaying = true;
_selectedIndex = index;
});
}
} else {
int result = await audioPlayer.stop();
if (result == 1) {
setState(() {
_isPlaying = false;
});
}
}
}
}
You're instantiating a new AudioPlayer audioPlayer object each time you call onPlay, which leaves you unable to stop that same player later.
Store your AudioPlayer audioPlayer in the state somewhere.
AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);
Future<void> onPlay({#required filepath, #required index}) async {
if (!_isPlaying) {
int result = await audioPlayer.play(filepath, isLocal: true);
if (result == 1) {
setState(() {
_isPlaying = true;
_selectedIndex = index;
});
}
} else {
int result = await audioPlayer.stop();
if (result == 1) {
setState(() {
_isPlaying = false;
});
}
}
}