isolate demo

dependencies
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2

  

main.dart

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_isolates_example/demo_isolates.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Isolates'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            DartIsolateWidget(),
            FlutterIsolateWidget(),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.home),
        onPressed: (){
          Navigator.of(context).push(MaterialPageRoute(builder: (context){
            return Test();
          }));
        },
      ),
    );
  }
}

class Test extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('test'),),
      body: Container(child: Text('just test'),),
    );
  }
}


class DartIsolateWidget extends StatefulWidget {
  @override
  _DartIsolateWidgetState createState() => _DartIsolateWidgetState();
}

class _DartIsolateWidgetState extends State<DartIsolateWidget> {
  StoppableIsolate isolate;

  @override
  Widget build(BuildContext context) => Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text(
                'Dart Isolates',
              ),
            ),
            Switch(
              value: isolate != null,
              onChanged: (bool checked) async {
                if (checked) {
                  StoppableIsolate isolate = await spawnIsolate();
                  setState(() {
                    this.isolate = isolate;
                  });
                } else {
                  isolate.stop();
                  setState(() {
                    isolate = null;
                  });
                }
              },
            ),
          ],
        ),
      );
}

class FlutterIsolateWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FlatButton(
      colorBrightness: Brightness.dark,
      color: Colors.blue,
      onPressed: () async {
        String result = await compute(flutterIsolateComputation, null);
        print('RECEIVED: ' + result);
      },
      child: Text(
        'Flutter Isolates',
      ),
    );
  }
}

  

demo_isolates.dart

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

Future<StoppableIsolate> spawnIsolate() async {
  ReceivePort receivePort = new ReceivePort();
  Isolate isolate = await Isolate.spawn(dartIsolateLongRunningOperation, receivePort.sendPort);
  receivePort.listen((data) {
    print('RECEIVED: ' + data);
  });
  return StoppableIsolate(isolate, receivePort);
}

// Isolate code
void dartIsolateLongRunningOperation(SendPort sendPort) async {
  while (true) {
    sleep(Duration(seconds: 3));
    sendPort.send('Dart: Worked for 3 seconds');
  }
}

class StoppableIsolate {
  final Isolate isolate;
  final ReceivePort receivePort;

  StoppableIsolate(this.isolate, this.receivePort);

  void stop() {
    receivePort.close();
    isolate.kill(priority: Isolate.immediate);
  }
}

// Isolate code
String flutterIsolateComputation(Null unused) {
  sleep(Duration(seconds: 3));
  return 'Flutter: Worked for 3 seconds';
}

  

原文地址:https://www.cnblogs.com/pythonClub/p/10768344.html