4

how to make app multi threading loop infinite flutter?

i tried to build flutter multi thread but failed, i want the while loop to run continuously and not stop the ui page,

can flutter be multi thread?

import 'package:flutter/material.dart';

import 'dart:isolate';
import 'dart:async';

void main() async {
  ReceivePort port = ReceivePort();

  await Isolate.spawn((SendPort sendPort) async {
    while (true) {
      // await Future.delayed(Duration.zero);
      sendPort.send("azka");
    }
  }, port.sendPort);

  port.listen((value) {
    print(value);
  });

  runApp(
    MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    ),
  );
}
noobdev
  • 95
  • 1
  • 6
  • Keep in mind that while the code within `Isolate.spawn(...)` can run on another thread, `port.listen((value) { print(value); })` is still being executed on the UI thread. It isn't very surprising that the UI thread is being overwhelmed in this case. Think of it this way, the second thread is sending the main thread messages as fast as it can create them, and the first thread is responsible for receiving all of these messages, printing each message, and also rendering the UI. – mmcdon20 Mar 19 '22 at 02:55
  • You can either 1. Move the printing to within the `Isolate.spawn`, and then you wouldn't even need to listen for messages on the port. 2. Add a delay, it doesn't necessarily need to be a very big delay, but it certainly needs to be longer than `Duration.zero`. – mmcdon20 Mar 19 '22 at 03:11

0 Answers0