Flutter Socket:How to get async resut in when i use socket.listen() many times in flutter? - flutter

Why can't I get results of listen2? How do I modify it?In the sample,I can only access the listen1 results but not the listen2 results。i am new
sample code:
Future<List<int>> getResult() async {
var a = creatDataToken();
var e= await Socket.connect(MyApp.host, MyApp.port).then((Socket socket) async{
socket.add(a);
socket.listen((List<int> listen1) async{
debugPrint('result listen1 :$listen1');
List<int> loginList= creatDataLogin(listen1);
await Socket.connect(MyApp.host, MyApp.port).then((Socket socket) async {
socket.add(loginList);
debugPrint('add:$loginList');
await socket.listen((List<int> listen2) {
debugPrint('result listen2 :$listen2');
return listen2;
});
});
});
});
enter image description here

bool flag;
Future getResult() async {
flag = false;
var a = creatDataToken() ;
var b= await Socket.connect(MyApp.host, MyApp.port).then((Socket socket){
mSocket=socket;
mSocket.add(a);
mSocket.addError((e){debugPrint('---addError--$e');});
mSocket.listen(onReceiver);
}).catchError((error){
debugPrint('---catchError--$error');
ToastUtils.showShortToast('username or password error!');
return;
});
return b;
}
void onReceiver(List<int> event) {
if(!flag){
debugPrint('result listen1 :$event');
flag=true;
List<int> loginList= creatDataLogin(event);
debugPrint('loginList:$loginList');
mSocket.add(loginList);
}else{
debugPrint('result listen2 :$event');
resolveResult(event);
}
}

Related

How to get value from Future in flutter

I'm trying to make a currency converter app in flutter.
The process I've planned was..
At the initState, get current currency data from API
Get currency data and assign it to 'currentCur'
Calculate converted currency value with 'currentCur' and display the value
But, I got an error that since 'currentCur' is Instance of 'Future<dynamic' so it can't calculated cause it is not subtype of 'num'
How can I get just value from Future in initState?
class _ConverterWidgetState extends State<ConverterWidget> {
late final TextEditingController _current;
late final currentCur;
late final currency;
fetchData() async {
try {
http.Response response = await http.get(
Uri.parse(
'https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRWUSD',
),
);
String jsonData = response.body;
var basePrice = jsonDecode(jsonData)[0]['basePrice'];
devtools.log(basePrice.toString());
return basePrice;
} catch (e) {
devtools.log(e.toString());
}
}
getCurrency(a) async {
return await Future.value(a);
}
#override
void initState() {
super.initState();
_current = TextEditingController(text: 1000.toString());
currentCur = fetchData();
devtools.log(currentCur.toString());
}
Specify the function is going to return a value with the "Future" keyWord
Future<num> fetchData() async {
var basePrice = 0;
try {
http.Response response = await http.get(
Uri.parse(
'https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRWUSD',
),
);
String jsonData = response.body;
basePrice = jsonDecode(jsonData)[0]['basePrice'];
devtools.log(basePrice.toString());
} catch (e) {
devtools.log(e.toString());
}
return basePrice;
}
void updateCurrentCur ()async{
var basePrice = await fetchData();
setState(() {
currentCur = basePrice;
});
}
#override
void initState() {
super.initState();
updateCurrentCur()
}

How to pass data between isolates in flutter dart

I am buiding an app were I want to run a batch operation in firestore and I want to run it in a different isolate. Here is my code for spawning the isolate:
Future<void> _startAnotherIsolate(String mediaUrl) async {
final isolate = await FlutterIsolate.spawn(isolate1,"hello"); // i need to pass 2 more
arguments
Timer(Duration(seconds: 5), () {
print("Pausing Isolate 1");
isolate.pause();
});
Timer(Duration(seconds: 10), () {
print("Resuming Isolate 1");
isolate.resume();
});
Timer(Duration(seconds: 20), () {
print("Killing Isolate 1");
isolate.kill();
});
}
My code for the isolate:
void isolate1(String data1, String data2) async {
await Firebase.initializeApp();
print("changing profile picture: $phone");
Timer.periodic(Duration(seconds: 1), (timer) => print("Timer Running From Isolate 1"));
var db = FirebaseFirestore.instance;
var batch = db.batch();
FirebaseFirestore.instance.collection("posts").doc(phone).collection("userPosts")
.get().then((querySnapshot) {
for (var document in querySnapshot.docs) {
try {
batch.update(document.reference,{'user_image': mediaUrl});
} on FormatException catch (error) {
// If a document ID is unparsable. Example "lRt931gu83iukSSLwyei" is unparsable.
// print("The document ${error.source} could not be parsed.");
return null;
}
}
return batch.commit();
});
}
I have seen This link and this link but they are not helpful
import 'dart:isolate';
class RequiredArgs {
late final SendPort sendPort;
late int id;
RequiredArgs(this.id, this.sendPort);
}
Future<void> main() async {
ReceivePort receivePort = ReceivePort();
RequiredArgs requiredArgs = RequiredArgs(1122, receivePort.sendPort);
Isolate isolate = await Isolate.spawn(download, requiredArgs);
var resp = await receivePort.first;
print(resp);
}
void download(RequiredArgs requiredArgs) {
final SendPort sendPort = requiredArgs.sendPort;
final id = requiredArgs.id;
print(id);
sendPort.send("yes");
}
We pass the value using the RequiredArgs class. Hope my answer helps.

Flutter/Dart convert future bool to bool

Can some one help me to identify the issue in below piece of code
void main() async {
bool c =getstatus();
print(c);
}
Future<bool> getMockData() {
return Future.value(false);
}
bool getstatus() async
{
Future<bool> stringFuture = getMockData();
bool message = stringFuture;
return(message); // will print one on console.
}
To get values from a Future(async) method, you have to await them. And after await the variable you get is not a Future anymore. So basically your code should look like this:
void main() async {
bool c = await getstatus();
print(c);
}
Future<bool> getMockData() {
return Future.value(false);
}
Future<bool> getstatus() async {
bool message = await getMockData();
return message;
}
Future<bool> stringFuture = await getMockData();
an async method must return Future of something then in the main you have to get the bool value by writing await
void main() async {
bool c = await getstatus();
print(c); // will print false on the console.
}
Future<bool> getMockData() {
return Future.value(false);
}
Future<bool> getstatus() async {
Future<bool> stringFuture = await getMockData();
return stringFuture; // will return false.
}

How do you check if an async void method is completed in Dart?

How do you check if an async void method is completed in Dart?
Method 1:
await voidFoo();
print("the above function was completed");
Future<void> voidFoo() async{
await Future.delayed(Duration(seconds:1));
}
Method 2:
Using a boolean variable like this,
bool isCompleted = false;
...
await voidFoo();
Future<void> voidFoo() async{
await Future.delayed(Duration(seconds:1));
isCompleted = true; //assuming isCompleted can be accessed here
}
There are too many methods to do this
i prefer to do this
Future<void> myFunction() async {
await Future.delayed(Duration(seconds: 3)); // your future operation
}
main() async {
await myFunction();
print("finished");
}
You can use dart Completer.
import 'dart:async';
void main() async {
final completer = Completer<String>();
Future<String> getHttpData()async{
return Future.delayed(const Duration(seconds: 1), () => "Future Result");
}
Future<String> asyncQuery()async {
final httpResponse = await getHttpData();
completer.complete(httpResponse);
return completer.future;
}
print('IsCompleted: ${completer.isCompleted}');
await asyncQuery();
print('IsCompleted: ${completer.isCompleted}');
}
Result;
IsCompleted: false
IsCompleted: true

Flutter flutter_in_app_purchases subscription FlutterInAppPurchses.instance.getSubscriptions() is not retrieving any items for IAPItem

I'm trying to implement a renewable subscription in flutter using the flutter_in_app_purchases plugin. When I click on the screen that this is declared in, it goes through the initState() function and then gets to the initPlatformState() and goes through that successfully, but when it gets to the getProducts() function, it's returning an empty item list for the List items = FlutterInappPurchase.instance.getSubscriptions([productID]); call. I've added the monthly subscription in both the App Store Connect and Google Play Store and completed the tax forms. Any help would be appreciated.
List<IAPItem> _items = [];
static const String productID = 'monthly_subscription';
#override
void initState() {
super.initState();
print("IN INIT STATE");
initPlatformState();
}
Future<void> initPlatformState() async {
print("In init platform state");
// prepare
final bool available = await InAppPurchaseConnection.instance.isAvailable();
print(available);
var close = await FlutterInappPurchase.instance.endConnection;
var result = await FlutterInappPurchase.instance.initConnection;
print('result: $result');
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) {
print('In not mounded');
return;
}
// refresh items for android
/*try {
String msg = await FlutterInappPurchase.instance.consumeAllItems;
print('consumeAllItems: $msg');
} catch(e){
print(e.toString());
}*/
await _getProduct();
}
Future<Null> _getProduct() async {
print("In get products");
try {
List<IAPItem> items = await FlutterInappPurchase.instance.getSubscriptions([productID]);
print("Items is: $items");
for (var item in items) {
print('${item.toString()}');
this._items.add(item);
}
setState(() {
this._items = items;
});
} catch(e) {
print(e.toString());
}
}
Here you have a working example from app in production. Disclaimer: I'm not using it anymore but the last time I did it worked fine:
class _InAppState extends State<InApp> {
StreamSubscription _purchaseUpdatedSubscription;
StreamSubscription _purchaseErrorSubscription;
StreamSubscription _conectionSubscription;
final List<String> _productLists = Platform.isAndroid
? [
'subs_premium', 'subs_user'
]
: ['subs_premium', 'subs_boss', 'subscripcion_user'];
String _platformVersion = 'Unknown';
List<IAPItem> _items = [];
List<IAPItem> _subscripions = [];
List<PurchasedItem> _purchases = [];
#override
void initState() {
super.initState();
initPlatformState();
}
#override
void dispose() {
super.dispose();
if (_conectionSubscription != null) {
_conectionSubscription.cancel();
_conectionSubscription = null;
}
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await FlutterInappPurchase.instance.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// prepare
var result = await FlutterInappPurchase.instance.initConnection;
print('result: $result');
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
// refresh items for android
try {
String msg = await FlutterInappPurchase.instance.consumeAllItems;
print('consumeAllItems: $msg');
} catch (err) {
print('consumeAllItems error: $err');
}
_conectionSubscription = FlutterInappPurchase.connectionUpdated.listen((connected) {
print('connected: $connected');
});
_purchaseUpdatedSubscription = FlutterInappPurchase.purchaseUpdated.listen((productItem) {
print('purchase-updated: $productItem');
});
_purchaseErrorSubscription = FlutterInappPurchase.purchaseError.listen((purchaseError) {
print('purchase-error: $purchaseError');
});
final List<String> _SKUS = widget.premium ? ['subs_boss']
: ['subs_user'] ;
_getSubscriptions(_SKUS);
}
void _requestPurchase(IAPItem item) {
FlutterInappPurchase.instance.requestPurchase(item.productId);
}
Future _getProduct() async {
print('TEST 1 HERE ${_productLists.length}, ${_productLists.first.toString()}');
List<IAPItem> items = await FlutterInappPurchase.instance.getProducts(_productLists);
print('TEST 2 HERE ${items.length}');
for (var item in items) {
print('${item.toString()}');
this._items.add(item);
}
setState(() {
this._items = items;
this._purchases = [];
});
}
Future _getPurchases() async {
List<PurchasedItem> items =
await FlutterInappPurchase.instance.getAvailablePurchases();
for (var item in items) {
print('${item.toString()}');
this._purchases.add(item);
}
setState(() {
this._items = [];
this._purchases = items;
});
}
Future _getSubscriptions(_SKUS) async {
List<IAPItem> items =
await FlutterInappPurchase.instance.getSubscriptions(_SKUS);
for (var item in items) {
print('${item.toString()}');
this._subscripions.add(item);
}
setState(() {
this._items = [];
this._subscripions = items;
});
}
Future _getPurchaseHistory() async {
List<PurchasedItem> items = await FlutterInappPurchase.instance.getPurchaseHistory();
for (var item in items) {
print('${item.toString()}');
this._purchases.add(item);
}
setState(() {
this._items = [];
this._purchases = items;
});
}