Skip to content

Commit

Permalink
Add a new page on "Concurrency and isolates" (flutter#9777)
Browse files Browse the repository at this point in the history
Adds documentation about using isolates in Flutter apps.

**Staged:**
https://flutter-docs-prod--pr9777-isolate-doc-update-ru4mbku4.web.app/perf/isolates

This will address
[6564](flutter#6564), albeit in a
different way than suggested.

---------

Co-authored-by: Brett Morgan <[email protected]>
Co-authored-by: Parker Lougheed <[email protected]>
Co-authored-by: Shams Zakhour (ignore Sfshaza) <[email protected]>
  • Loading branch information
4 people authored and Tony Sansone committed Dec 11, 2023
1 parent 94f9d0b commit 2f77363
Show file tree
Hide file tree
Showing 10 changed files with 482 additions and 1 deletion.
10 changes: 10 additions & 0 deletions examples/development/concurrency/isolates/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Take our settings from the example_utils analysis_options.yaml file.
# If necessary for a particular example, this file can also include
# overrides for individual lints.

include: package:example_utils/analysis.yaml

linter:
rules:
avoid_print: false
prefer_const_constructors: false
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import 'dart:isolate';

import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
// Identify the root isolate to pass to the background isolate.
RootIsolateToken rootIsolateToken = RootIsolateToken.instance!;
Isolate.spawn(_isolateMain, rootIsolateToken);
}

Future<void> _isolateMain(RootIsolateToken rootIsolateToken) async {
// Register the background isolate with the root isolate.
BackgroundIsolateBinaryMessenger.ensureInitialized(rootIsolateToken);

// You can now use the shared_preferences plugin.
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

print(sharedPreferences.getBool('isDebug'));
}
71 changes: 71 additions & 0 deletions examples/development/concurrency/isolates/lib/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright 2021 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:convert';
import 'dart:isolate';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Isolates demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Isolates demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
getPhotos();
},
child: Text('Fetch photos'),
),
),
),
);
}
}

// #docregion isolate-run
// Produces a list of 211,640 photo objects.
// (The JSON file is ~20MB.)
Future<List<Photo>> getPhotos() async {
final String jsonString = await rootBundle.loadString('assets/photos.json');
final List<Photo> photos = await Isolate.run<List<Photo>>(() {
final List<Object?> photoData = jsonDecode(jsonString) as List<Object?>;
return photoData.cast<Map<String, Object?>>().map(Photo.fromJson).toList();
});
return photos;
}
// #enddocregion isolate-run

class Photo {
final int albumId;
final int id;
final String title;
final String thumbnailUrl;

Photo({
required this.albumId,
required this.id,
required this.title,
required this.thumbnailUrl,
});

factory Photo.fromJson(Map<String, dynamic> data) {
return Photo(
albumId: data['albumId'] as int,
id: data['id'] as int,
title: data['title'] as String,
thumbnailUrl: data['thumbnailUrl'] as String,
);
}
}
17 changes: 17 additions & 0 deletions examples/development/concurrency/isolates/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: isolates
description: Sample isolate code

version: 1.0.0+1

environment:
sdk: ^3.1.0

dependencies:
flutter:
sdk: flutter
shared_preferences: any

dev_dependencies:
example_utils:
path: ../../../example_utils

2 changes: 2 additions & 0 deletions src/_data/sidenav.yml
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,8 @@
permalink: /perf/shader
- title: Performance metrics
permalink: /perf/metrics
- title: Concurrency and isolates
permalink: /perf/isolates
- title: Performance FAQ
permalink: /perf/faq
- title: Appendix
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion src/cookbook/networking/background-parsing.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ class PhotosList extends StatelessWidget {

![Isolate demo]({{site.url}}/assets/images/docs/cookbook/isolate.gif){:.site-mobile-screenshot}

[`compute()`]: {{site.api}}/flutter/foundation/compute-constant.html
[`compute()`]: {{site.api}}/flutter/foundation/compute.html
[Fetch data from the internet]: {{site.url}}/cookbook/networking/fetch-data
[`http`]: {{site.pub-pkg}}/http
[`http.get()`]: {{site.pub-api}}/http/latest/http/get.html
Expand Down
Loading

0 comments on commit 2f77363

Please sign in to comment.