Calling SharedPreferences in didChangeDependencies - flutter

Can you call a boolean with Shared Preferences in didChangeDependencies?
I need to use isToolTipTapped as a conditional in my build method but it doesn't seem to be working..
#override
void didChangeDependencies() async {
isToolTipTapped = await checkIfToolTipTapped();
print('$isToolTipTapped');
super.didChangeDependencies();
}
Future<bool> checkIfToolTipTapped() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool(SchnapConfigValues.toolTipTapped ?? false);
}
print('$isToolTipTapped'); does return the boolean in didChangeDependencies method but my build method doesn't take the value

I think you should be try this code:
class _DemoPageState extends State<DemoPage> {
static const TAG = 'DemoPage';
bool isToolTipTapped;
Future<bool> checkIfToolTipTapped() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool(SchnapConfigValues.toolTipTapped ?? false);
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
checkIfToolTipTapped().then((value) {
setState(() {
isToolTipTapped = value;
});
});
}
#override
Widget build(BuildContext context) {
if (isToolTipTapped == null) {
return Your Loading Widget...
} else {
//Handle logic with isToolTipTapped
}
}
}

class _DemoPageState extends State<DemoPage> {
static const TAG ='DemoPage';
bool isToolTipTapped = false;
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<bool> checkIfToolTipTapped() async {
SharedPreferences prefs = await _prefs;
return prefs.getBool(SchnapConfigValues.toolTipTapped ?? false);
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
checkIfToolTipTapped().then((value) {
setState(() {
isToolTipTapped = value;
});
});
}
#override Widget build(BuildContext context) {
if (isToolTipTapped) {
return Your Loading Widget...
} else {
//Handle logic with isToolTipTapped
}
}
}

Related

how to forward a method in a file

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();
});
}
}
}

currentUser: The expression doesn't evaluate to a function, so it can't be invoked

I need to update this code, not I'm not sure how. Does anyone have a clue?
_initialize() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
bool loggedIn = prefs.getBool(LOGGED_IN) ?? false;
if(!loggedIn){
_status = Status.Unauthenticated;
}else{
await auth.currentUser().then((currentUser) async{
_user = currentUser;
_status = Status.Authenticated;
_userModel = await _userServices.getUserById(currentUser.uid);
});
}
notifyListeners();
}
"currentUser" is not a method anymore, it's a property.
_initialize() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
bool loggedIn = prefs.getBool(LOGGED_IN) ?? false;
if(!loggedIn){
_status = Status.Unauthenticated;
}else{
_user = auth.currentUser;
_status = Status.Authenticated;
_userModel = await _userServices.getUserById(_user.uid);
}
notifyListeners();
}

Failed assertion: line 4397 pos 12: '_lifecycleState != _ElementLifecycle.defunct': is not true

im getting this error
When using this code in initstate
VideoPlayerController videoPlayerController;
bool stopvideo = false;
#override
void initState() {
super.initState();
videoPlayerController = VideoPlayerController.file(
widget.videourl,
)..initialize().then((value) {
videoPlayerController?.pause();
setState(() {
stopvideo = true;
});
videoPlayerController.setVolume(1);
videoPlayerController?.addListener(() {
if (videoPlayerController?.value != null) {
if (videoPlayerController.value?.duration ==
videoPlayerController.value?.position) {
if (this.mounted) {
setState(() {
stopvideo = true;
});
}
}
if (videoPlayerController.value.hasError) {
setState(() {
stopvideo = true;
});
}
}
});
});
}
The error happens because of this lines
videoPlayerController?.addListener(() {
if (videoPlayerController?.value != null) {
if (videoPlayerController.value?.duration ==
videoPlayerController.value?.position) {
if (this.mounted) {
setState(() {
stopvideo = true;
});
}
}
And I really have no idea why
Dispose looks like that
#override
void dispose() {
videoPlayerController?.pause();
videoPlayerController.removeListener(() {});
videoPlayerController?.dispose();
super.dispose();
}
I tried already removing the ? and a lot of other things but I cannot figure out what happened here .
Hope anyone can help .

Want to post geolocation on a external api using getx

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?

Flutter: Check Internet connectivity and navigate based on output?

I am new to flutter, I want to check whether the internet is available or not and based on the condition, the screen has to change. I have written the code below (screen switch is working properly), but I am not able to get bool output(internet). When I removed the Future in check internet class, it throws an error. Can you please solve the issue:
class _ScreenState extends State<ChannelScreen> {
bool isInternet;
bool result;
#override
void initState() {
// TODO: implement initState
result = check();
super.initState();
}
#override
Widget _buildChild() {
print ("The output “);
print (result);
if (result != Null && result == true) {
// if internet is ON
return Container();
}
//if internet is off
return Container();
}
Widget build(BuildContext context) {
return new Container(child: _buildChild());
}
}
Future<bool> check() async{
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.mobile) {
print ("******* Mobile is ON ******");
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
print ("******* Wifi is ON ******");
return true;
}
print ("No connectivity");
return false;
}
You can use StreamBuilder
StreamBuilder(
stream: Connectivity().onConnectivityChanged,
builder: (context, snapshot) {
// Use this to avoid null exception
if (snapshot.connectionState == ConnectionState.none) {
return CircularProgressIndicator();
} else {
ConnectivityResult result = snapshot.data;
// Check Connectivity result here and display your widgets
if(ConnectivityResult.none) {
yourWidgetForNoInternet();
} else {
yourWidgetForInternet();
}
}
},
)
bool hasInternet = false, isChecking = true;
#override
void initState() {
super.initState();
check();
}
#override
Widget build(BuildContext context) {
return Container(
child: isChecking
? ListTile(
leading: CircularProgressIndicator(), title: Text('Checking...'))
: hasInternet
? ListTile(title: Text('Your widget here...'))
: ListTile(
leading: Icon(Icons.info),
title: Text('No Internet Conncetion')));
}
check() async {
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.mobile) {
print("******* Mobile is ON ******");
setState(() {
isChecking = false;
hasInternet = true;
//navigate to another screen.....
});
} else if (connectivityResult == ConnectivityResult.wifi) {
print("******* Wifi is ON ******");
setState(() {
isChecking = false;
hasInternet = true;
//navigate to another screen.....
});
} else {
setState(() {
isChecking = false;
hasInternet = false;
});
}
}
There is a plugin to use connectivity:
https://pub.dev/packages/connectivity#-readme-tab-
I use following code to check whether the internet is connected or not
static Future<bool> checkInternetConnectivity() async {
bool isConnected;
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
isConnected = true;
}
} on SocketException catch (_) {
isConnected = false;
}
return isConnected;
}