forked from flutter/flutter
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sample code for ImageProvider (flutter#131952)
Also: - minor improvements to documentation - wrap one of our test error messages in a manner more consistent with other messages
- Loading branch information
Showing
7 changed files
with
178 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
104 changes: 104 additions & 0 deletions
104
examples/api/lib/painting/image_provider/image_provider.0.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
// Copyright 2014 The Flutter Authors. 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:async'; | ||
import 'dart:io'; | ||
import 'dart:ui' as ui; | ||
|
||
import 'package:flutter/foundation.dart'; | ||
import 'package:flutter/material.dart'; | ||
|
||
@immutable | ||
class CustomNetworkImage extends ImageProvider<Uri> { | ||
const CustomNetworkImage(this.url); | ||
|
||
final String url; | ||
|
||
@override | ||
Future<Uri> obtainKey(ImageConfiguration configuration) { | ||
final Uri result = Uri.parse(url).replace( | ||
queryParameters: <String, String>{ | ||
'dpr': '${configuration.devicePixelRatio}', | ||
'locale': '${configuration.locale?.toLanguageTag()}', | ||
'platform': '${configuration.platform?.name}', | ||
'width': '${configuration.size?.width}', | ||
'height': '${configuration.size?.height}', | ||
'bidi': '${configuration.textDirection?.name}', | ||
}, | ||
); | ||
return SynchronousFuture<Uri>(result); | ||
} | ||
|
||
static HttpClient get _httpClient { | ||
HttpClient? client; | ||
assert(() { | ||
if (debugNetworkImageHttpClientProvider != null) { | ||
client = debugNetworkImageHttpClientProvider!(); | ||
} | ||
return true; | ||
}()); | ||
return client ?? HttpClient()..autoUncompress = false; | ||
} | ||
|
||
@override | ||
ImageStreamCompleter loadImage(Uri key, ImageDecoderCallback decode) { | ||
final StreamController<ImageChunkEvent> chunkEvents = StreamController<ImageChunkEvent>(); | ||
debugPrint('Fetching "$key"...'); | ||
return MultiFrameImageStreamCompleter( | ||
codec: _httpClient.getUrl(key) | ||
.then<HttpClientResponse>((HttpClientRequest request) => request.close()) | ||
.then<Uint8List>((HttpClientResponse response) { | ||
return consolidateHttpClientResponseBytes( | ||
response, | ||
onBytesReceived: (int cumulative, int? total) { | ||
chunkEvents.add(ImageChunkEvent( | ||
cumulativeBytesLoaded: cumulative, | ||
expectedTotalBytes: total, | ||
)); | ||
}, | ||
); | ||
}) | ||
.catchError((Object e, StackTrace stack) { | ||
scheduleMicrotask(() { | ||
PaintingBinding.instance.imageCache.evict(key); | ||
}); | ||
return Future<Uint8List>.error(e, stack); | ||
}) | ||
.whenComplete(chunkEvents.close) | ||
.then<ui.ImmutableBuffer>(ui.ImmutableBuffer.fromUint8List) | ||
.then<ui.Codec>(decode), | ||
chunkEvents: chunkEvents.stream, | ||
scale: 1.0, | ||
debugLabel: '"key"', | ||
informationCollector: () => <DiagnosticsNode>[ | ||
DiagnosticsProperty<ImageProvider>('Image provider', this), | ||
DiagnosticsProperty<Uri>('URL', key), | ||
], | ||
); | ||
} | ||
|
||
@override | ||
String toString() => '${objectRuntimeType(this, 'CustomNetworkImage')}("$url")'; | ||
} | ||
|
||
void main() => runApp(const ExampleApp()); | ||
|
||
class ExampleApp extends StatelessWidget { | ||
const ExampleApp({super.key}); | ||
|
||
@override | ||
Widget build(BuildContext context) { | ||
return MaterialApp( | ||
home: LayoutBuilder( | ||
builder: (BuildContext context, BoxConstraints constraints) { | ||
return Image( | ||
image: const CustomNetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/flamingos.jpg'), | ||
width: constraints.hasBoundedWidth ? constraints.maxWidth : null, | ||
height: constraints.hasBoundedHeight ? constraints.maxHeight : null, | ||
); | ||
}, | ||
), | ||
); | ||
} | ||
} |
20 changes: 20 additions & 0 deletions
20
examples/api/test/painting/image_provider/image_provider.0_test.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
// Copyright 2014 The Flutter Authors. All rights reserved. | ||
// Use of this source code is governed by a BSD-style license that can be | ||
// found in the LICENSE file. | ||
|
||
import 'package:flutter/foundation.dart'; | ||
import 'package:flutter_api_samples/painting/image_provider/image_provider.0.dart'; | ||
import 'package:flutter_test/flutter_test.dart'; | ||
|
||
void main() { | ||
testWidgets('$CustomNetworkImage', (WidgetTester tester) async { | ||
const String expectedUrl = 'https://flutter.github.io/assets-for-api-docs/assets/widgets/flamingos.jpg?dpr=3.0&locale=en-US&platform=android&width=800.0&height=600.0&bidi=ltr'; | ||
final List<String> log = <String>[]; | ||
final DebugPrintCallback originalDebugPrint = debugPrint; | ||
debugPrint = (String? message, {int? wrapWidth}) { log.add('$message'); }; | ||
await tester.pumpWidget(const ExampleApp()); | ||
expect(tester.takeException().toString(), 'Exception: Invalid image data'); | ||
expect(log, <String>['Fetching "$expectedUrl"...']); | ||
debugPrint = originalDebugPrint; | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters