简体   繁体   中英

How to pass data between isolates in flutter dart

I am buiding app were I want to run batch operation in firestore and so 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM