Protractor click if displayed is not working using async await - protractor

Protractor click if displayed is not working using async await. I have tried with the following method:
public static async clickIfDisplayed(targetElement: ElementFinder) {
if (await targetElement.isPresent() && await targetElement.isDisplayed()) {
await PageHelper.click(targetElement);
}
}
The above sometime clicks even if element is not present or displayed. Please help to understand where I am going wrong here.

The following worked well with async-await:
public static async clickIfDisplayed(targetElement: ElementFinder) {
const isPresent = await targetElement.isPresent();
if (isPresent) {
const isDisplayed = await targetElement.isDisplayed();
if (isDisplayed) {
await PageHelper.click(targetElement);
}
}
}

public static async clickIfDisplayed(targetElement: ElementFinder) {
await targetElement.isPresent().then(bool1 => {
await targetElement.isDisplayed().then (bool2 => {
if (bool1 && bool2) {
await PageHelper.click(targetElement);
}
});
}
}
Does this work?

Related

how to create a stream in flutter that return a bool in every second

i am making a app. And i want to check my server state every minite and give user information
about the server. How do i do it. is stream good for it. Can some provide me a code for that.
just follow this guide
suppose your bool return value function is
Future<bool> isGpsOn() async {
return await Geolocator().isLocationServiceEnabled();
}
and this is create stream from bool value
Stream futureToStream(fn, defaultValue, Duration duration) async* {
var result;
while (true) {
try {
result = await fn();
}
catch (error) {
result = defaultValue;
}
finally {
yield result;
}
await Future.delayed(duration);
}
}
final gpsStatusStream = futureToStream(isGpsOn, false, Duration(seconds: 5));
gpsStatusStream.listen((enabled) {
print(enabled ? 'enabled' : 'disabled');
});
Use asyncMap
Stream<String> checkConnectionStream() async* {
yield* Stream.periodic(Duration(seconds: 1), (_) {
return //your function
}).asyncMap((event) async => await event);
}

Flutter : Flutter Shared Preference don't work ,not save username Edit#1

I have an app contain login and register system ,the system is working correctly.
the problem is I want to keep user logged in by using flutter_session package but don't work.
first I have preloading page contain checking if user is logged in by using functions below :
void gotoTabPae() {
print('ok');
Future.delayed(const Duration(milliseconds: 3000), () {
Navigator.of(context).pushReplacementNamed('tabs');
});
}
void gotoLoginPage() {
print('no');
Future.delayed(const Duration(milliseconds: 3000), () {
Navigator.of(context).pushReplacementNamed('login');
});
}
getuser() async {
var loginedUser;
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
loginedUser= preferences.getString('username');
});
loginedUser != null ? gotoTabPae() : gotoLoginPage();
}
#override
void initState() {
getuser();
super.initState();
}
when I run the app and login then when I restart the app it must go to 'tabs' page ,but the value of username is always null therefore it load login page ,the login function is :
login() async {
var formdata = formLoginKey.currentState;
if (formdata.validate()) {
formdata.save();
var data = {'username': username.text, 'password': password.text};
var url =xxxx/api/controller/users/login_user.php";
var response = await http.post(url, body: data);
var responsebody = jsonDecode(response.body);
if (responsebody['status'] == 'success') {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString('username', username.text);
Navigator.of(context).pushReplacementNamed('tabs');
} else {
_showDialog(context, responsebody['status']);
}
} else {
}
}
But in tabs page it is load the session username corret :
getuser() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
var logineduser = preferences.getString('username');
}
#override
void initState() {
getuser();
super.initState();
}
How can I solve this? where is my mistake ?
Your code is running the getuser() method in the initSate() method that too even before the super.initState();. That is the reason the value is no able to load which makes it null. You should use it in the build function.
Your code might look like this:
#override
Widget build(BuildContext context) {
var loginedUser;
loginedUser = await FlutterSession().get('username');
loginedUser != null ? return ClassName()(tabs.dart) : return ClassName()(login.dart);
}
I think that in your login function, pref.setString('username', username.text) is run before the response is received. Can you try this:
http.post(url, body: data).then((response) {
var responsebody = jsonDecode(response.body);
if (responsebody['status'] == 'success') {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setString('username', username.text);
Navigator.of(context).pushReplacementNamed('tabs');
}
});
and let me know the result?

Flutter:How I create a Hive DAO class in flutter/dart?

I need to group all operations of a Hivebd crud get, put, delete and update in one class but when I try this get a error because Hive.openBox() need an await but constructors not allowed async.How I would do that corectely?
My class below.
class HomeListRepository {
var _homelistStore = await Hive.openBox<HomeList>("homelists");
Future insert(String id, HomeList homelist) async {
await _homelistStore.put(id,homelist.toMap());
}
Future update(HomeList homelist) async {
await _homelistStore.put(homelist.id,homelist.toMap());
}
Future delete(HomeList homelist) async {
await _homelistStore.delete(homelist.id);
}
Future<List<HomeList>> getAll() async {
return _homelistStore.values;
}
}
Edit:
I solved this and the final code is:
class HomeListRepository {
Box _homelistStore;
Future<void> insert(String id,HomeList homelist) async {
_homelistStore = await Hive.openBox<HomeList>("homelists");
_homelistStore.put(id,homelist);
}
Future<void> update(HomeList homelist) async {
_homelistStore = await Hive.openBox<HomeList>("homelists");
await _homelistStore.put(homelist.id,homelist);
}
Future<void> delete(HomeList homelist) async {
_homelistStore = await Hive.openBox<HomeList>("homelists");
await _homelistStore.delete(homelist.id);
}
Future<List<HomeList>> readAll() async {
_homelistStore = await Hive.openBox<HomeList>("homelists");
return _homelistStore.values.toList();
}
}
finded on Hive github page:GitHub

Race condition with stream listen

I have an async function like below. However content is being returned null well before the stream listening is done.
I started playing out with Future.delayed, but thought better of it and wanted to ask if there is a better approach to ensure this is async?
import 'package:googleapis/drive/v3.dart' as ga;
static Future<String> getContentsFromFile() async {
String content;
ga.Media mediaResponse = await drive.files.get(fileId);
mediaResponse.stream.listen((data) {
print("DataReceived: "+data);
content = data
}, onDone: () async {
print("Task Done");
}, onError: (error) {
print("Some Error");
});
return content;
}
Im calling the function like so..
String content = await getContentsFromFile();
EDIT: Made the example more complete, with handling of errors and partial content.
You can use Completer for this sort of control flow:
import 'dart:async';
import 'package:googleapis/drive/v3.dart' as ga;
static Future<String> getContentsFromFile() async {
Completer<String> completer = Completer();
String content = "";
ga.Media mediaResponse = await drive.files.get(fileId);
mediaResponse.stream.listen((data) {
print("DataReceived: "+data);
content += data;
}, onDone: () async {
print("Task Done");
completer.complete(content);
}, onError: (error) {
print("Some Error");
completer.completeError(error);
});
return completer.future;
}

How to post observer from normal class and receive listener to widget?

I'm pretty new to Flutter and experimenting with the SDK. I am working with the flutter application which works with Socket connection. I saw lots of example which communicate with widget to widget. But, I want to add listener from Socket class to widgets. The actual scenario is, I have socket listeners in my socket manager class. Here is the rough code for better idea.
class SocketManager {
static SocketIO socketIO;
static SocketIOManager manager = SocketIOManager();
//Constructor
SocketManager(){
initSocket().then((socketIO){
addListener();
});
}
void addListener(){
socketIO.onConnect((data){
print("connected...");
});
}
}
I want to notify to my widgets when socket connected.
What kind of thing am I looking for to implement this?
Thanks in advance.
here is my class, you can follow to create yours
import 'dart:convert';
import 'package:flutter_app/global.dart';
import 'package:flutter_app/strings.dart';
import 'package:rxdart/subjects.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;
IO.Socket kSocket;
class Sockets {
static PublishSubject socket = PublishSubject(sync: true);
static PublishSubject status = PublishSubject(sync: true);
static PublishSubject notify = PublishSubject(sync: true);
static PublishSubject chatCount = PublishSubject(sync: true);
static PublishSubject typing = PublishSubject(sync: true);
static PublishSubject login = PublishSubject(sync: false);
static PublishSubject getInfo = PublishSubject(sync: true);
static PublishSubject alreadyLogin = PublishSubject(sync: false);
static void connectSocket() async {
/* kSocket = await IO.io('${Strings.socket}', <String, dynamic>{
'transports': ['websocket', 'polling'],
});*/
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString('userToken');
if (token != null && token != '') {
Map<String, dynamic> parsedToken = Functions.parseJwt(token);
String imza = token?.split('.')[2];
kSocket = await IO.io('${Strings.socket}', <String, dynamic>{
'transports': ['websocket', 'polling'],
'query': 'token=$imza'
});
parsedToken['Tur'] = 2;
kSocket.close();
kSocket.disconnect();
kSocket.open();
try {
kSocket.on('connect', (data) {
print('SOCKET CONNECTED');
kSocket.emit('adduser', parsedToken);
kSocket.on('getmessage', (res) {
print('GETMSG: $res');
chatCount.sink.add(res);
socket.sink.add(res);
});
kSocket.on('bildirim', (res) {
print('[BILDIRIM]: $res');
notify.sink.add(res);
});
kSocket.on('durum', (res) {
status.sink.add(res);
});
kSocket.on('disconnect', (data) {
// print('DISCONNECT: $data');
});
kSocket.on('typing', (res) {
typing.sink.add(res);
});
kSocket.on('login', (res) {
//print('Multi Login');
login.sink.add(res);
});
kSocket.on('getinfo', (res) {
//print('GETINFO: $res');
getInfo.sink.add(res);
});
kSocket.on('alreadylogin', (res) {
//print('ALREADY LOGIN: $res');
alreadyLogin.sink.add(res);
});
});
} catch (e) {
print(e);
}
} else {
print('SOCKET: token yok');
}
}
static void setInfo(Map<String, dynamic> data) {
kSocket.emit('setinfo', [data]);
}
static void setRead(String userid) {
kSocket.emit('setreaded', '$userid');
}
static void isTyping(String username, int status) {
kSocket.emit('istyping', [
{"user": int.parse(username), "durum": status}
]);
}
static void isActive(String userid) {
if (kSocket != null) {
if (kSocket.connected) {
try {
//print('${kSocket.connected}');
kSocket.emit('isactive', '$userid');
} catch (e) {
print(e);
}
}
}
}
static void disconnectSocket() async {
try {
await kSocket.disconnect();
await kSocket.close();
await kSocket.destroy();
print('SOCKET DISCONNECTED');
} catch (e) {
//print(e);
}
}
static void dispose(){
socket.close();
status.close();
//notify.close();
chatCount.close();
typing.close();
login.close();
getInfo.close();
alreadyLogin.close();
}
static void unSubNotify(){
notify.close();
}
}
Answer is here !! Here what I found while surfing on the web. Flutter-NotificationCenter. An IOS type post and receive observer. It is Very helpful to other developers who want to post observer from anywhere and want to receive it to anywhere.