text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 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.
/// This file shims dart:ui in web-only scenarios, getting rid of the need to
/// suppress analyzer warnings.
// TODO(ditman): Remove this file once web-only dart:ui APIs
// are exposed from a dedicated place, flutter/flutter#55000.
export 'dart_ui_fake.dart' if (dart.library.html) 'dart_ui_real.dart';
| plugins/packages/url_launcher/url_launcher_web/lib/src/shims/dart_ui.dart/0 | {
"file_path": "plugins/packages/url_launcher/url_launcher_web/lib/src/shims/dart_ui.dart",
"repo_id": "plugins",
"token_count": 141
} | 1,339 |
# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
end
end
| plugins/packages/video_player/video_player/example/ios/Podfile/0 | {
"file_path": "plugins/packages/video_player/video_player/example/ios/Podfile",
"repo_id": "plugins",
"token_count": 449
} | 1,340 |
// Copyright 2013 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.
// This file is used to extract code samples for the README.md file.
// Run update-excerpts if you modify this file.
// ignore_for_file: library_private_types_in_public_api, public_member_api_docs
// #docregion basic-example
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
void main() => runApp(const VideoApp());
/// Stateful widget to fetch and then display video content.
class VideoApp extends StatefulWidget {
const VideoApp({Key? key}) : super(key: key);
@override
_VideoAppState createState() => _VideoAppState();
}
class _VideoAppState extends State<VideoApp> {
late VideoPlayerController _controller;
@override
void initState() {
super.initState();
_controller = VideoPlayerController.network(
'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4')
..initialize().then((_) {
// Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
setState(() {});
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Video Demo',
home: Scaffold(
body: Center(
child: _controller.value.isInitialized
? AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: VideoPlayer(_controller),
)
: Container(),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_controller.value.isPlaying
? _controller.pause()
: _controller.play();
});
},
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
),
);
}
@override
void dispose() {
super.dispose();
_controller.dispose();
}
}
// #enddocregion basic-example
| plugins/packages/video_player/video_player/example/lib/basic.dart/0 | {
"file_path": "plugins/packages/video_player/video_player/example/lib/basic.dart",
"repo_id": "plugins",
"token_count": 842
} | 1,341 |
// Copyright 2013 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_test/flutter_test.dart';
import 'package:video_player/src/closed_caption_file.dart';
import 'package:video_player/video_player.dart';
void main() {
group('Parse VTT file', () {
WebVTTCaptionFile parsedFile;
test('with Metadata', () {
parsedFile = WebVTTCaptionFile(_valid_vtt_with_metadata);
expect(parsedFile.captions.length, 1);
expect(parsedFile.captions[0].start, const Duration(seconds: 1));
expect(parsedFile.captions[0].end,
const Duration(seconds: 2, milliseconds: 500));
expect(parsedFile.captions[0].text, 'We are in New York City');
});
test('with Multiline', () {
parsedFile = WebVTTCaptionFile(_valid_vtt_with_multiline);
expect(parsedFile.captions.length, 1);
expect(parsedFile.captions[0].start,
const Duration(seconds: 2, milliseconds: 800));
expect(parsedFile.captions[0].end,
const Duration(seconds: 3, milliseconds: 283));
expect(parsedFile.captions[0].text,
'— It will perforate your stomach.\n— You could die.');
});
test('with styles tags', () {
parsedFile = WebVTTCaptionFile(_valid_vtt_with_styles);
expect(parsedFile.captions.length, 3);
expect(parsedFile.captions[0].start,
const Duration(seconds: 5, milliseconds: 200));
expect(parsedFile.captions[0].end, const Duration(seconds: 6));
expect(parsedFile.captions[0].text,
"You know I'm so excited my glasses are falling off here.");
});
test('with subtitling features', () {
parsedFile = WebVTTCaptionFile(_valid_vtt_with_subtitling_features);
expect(parsedFile.captions.length, 3);
expect(parsedFile.captions[0].number, 1);
expect(parsedFile.captions.last.start, const Duration(seconds: 4));
expect(parsedFile.captions.last.end, const Duration(seconds: 5));
expect(parsedFile.captions.last.text, 'Transcrit par Célestes™');
});
test('with [hours]:[minutes]:[seconds].[milliseconds].', () {
parsedFile = WebVTTCaptionFile(_valid_vtt_with_hours);
expect(parsedFile.captions.length, 1);
expect(parsedFile.captions[0].number, 1);
expect(parsedFile.captions.last.start, const Duration(seconds: 1));
expect(parsedFile.captions.last.end, const Duration(seconds: 2));
expect(parsedFile.captions.last.text, 'This is a test.');
});
test('with [minutes]:[seconds].[milliseconds].', () {
parsedFile = WebVTTCaptionFile(_valid_vtt_without_hours);
expect(parsedFile.captions.length, 1);
expect(parsedFile.captions[0].number, 1);
expect(parsedFile.captions.last.start, const Duration(seconds: 3));
expect(parsedFile.captions.last.end, const Duration(seconds: 4));
expect(parsedFile.captions.last.text, 'This is a test.');
});
test('with invalid seconds format returns empty captions.', () {
parsedFile = WebVTTCaptionFile(_invalid_seconds);
expect(parsedFile.captions, isEmpty);
});
test('with invalid minutes format returns empty captions.', () {
parsedFile = WebVTTCaptionFile(_invalid_minutes);
expect(parsedFile.captions, isEmpty);
});
test('with invalid hours format returns empty captions.', () {
parsedFile = WebVTTCaptionFile(_invalid_hours);
expect(parsedFile.captions, isEmpty);
});
test('with invalid component length returns empty captions.', () {
parsedFile = WebVTTCaptionFile(_time_component_too_long);
expect(parsedFile.captions, isEmpty);
parsedFile = WebVTTCaptionFile(_time_component_too_short);
expect(parsedFile.captions, isEmpty);
});
});
test('Parses VTT file with malformed input.', () {
final ClosedCaptionFile parsedFile = WebVTTCaptionFile(_malformedVTT);
expect(parsedFile.captions.length, 1);
final Caption firstCaption = parsedFile.captions.single;
expect(firstCaption.number, 1);
expect(firstCaption.start, const Duration(seconds: 13));
expect(firstCaption.end, const Duration(seconds: 16));
expect(firstCaption.text, 'Valid');
});
}
/// See https://www.w3.org/TR/webvtt1/#introduction-comments
const String _valid_vtt_with_metadata = '''
WEBVTT Kind: captions; Language: en
REGION
id:bill
width:40%
lines:3
regionanchor:100%,100%
viewportanchor:90%,90%
scroll:up
NOTE
This file was written by Jill. I hope
you enjoy reading it. Some things to
bear in mind:
- I was lip-reading, so the cues may
not be 100% accurate
- I didn’t pay too close attention to
when the cues should start or end.
1
00:01.000 --> 00:02.500
<v Roger Bingham>We are in New York City
''';
/// See https://www.w3.org/TR/webvtt1/#introduction-multiple-lines
const String _valid_vtt_with_multiline = '''
WEBVTT
2
00:02.800 --> 00:03.283
— It will perforate your stomach.
— You could die.
''';
/// See https://www.w3.org/TR/webvtt1/#styling
const String _valid_vtt_with_styles = '''
WEBVTT
00:05.200 --> 00:06.000 align:start size:50%
<v Roger Bingham><i>You know I'm so excited my glasses are falling off here.</i>
00:00:06.050 --> 00:00:06.150
<v Roger Bingham><i>I have a different time!</i>
00:06.200 --> 00:06.900
<c.yellow.bg_blue>This is yellow text on a blue background</c>
''';
//See https://www.w3.org/TR/webvtt1/#introduction-other-features
const String _valid_vtt_with_subtitling_features = '''
WEBVTT
test
00:00.000 --> 00:02.000
This is a test.
Slide 1
00:00:00.000 --> 00:00:10.700
Title Slide
crédit de transcription
00:04.000 --> 00:05.000
Transcrit par Célestes™
''';
/// With format [hours]:[minutes]:[seconds].[milliseconds]
const String _valid_vtt_with_hours = '''
WEBVTT
test
00:00:01.000 --> 00:00:02.000
This is a test.
''';
/// Invalid seconds format.
const String _invalid_seconds = '''
WEBVTT
60:00:000.000 --> 60:02:000.000
This is a test.
''';
/// Invalid minutes format.
const String _invalid_minutes = '''
WEBVTT
60:60:00.000 --> 60:70:00.000
This is a test.
''';
/// Invalid hours format.
const String _invalid_hours = '''
WEBVTT
5:00:00.000 --> 5:02:00.000
This is a test.
''';
/// Invalid seconds format.
const String _time_component_too_long = '''
WEBVTT
60:00:00:00.000 --> 60:02:00:00.000
This is a test.
''';
/// Invalid seconds format.
const String _time_component_too_short = '''
WEBVTT
60:00.000 --> 60:02.000
This is a test.
''';
/// With format [minutes]:[seconds].[milliseconds]
const String _valid_vtt_without_hours = '''
WEBVTT
00:03.000 --> 00:04.000
This is a test.
''';
const String _malformedVTT = '''
WEBVTT Kind: captions; Language: en
00:09.000--> 00:11.430
<Test>This one should be ignored because the arrow needs a space.
00:13.000 --> 00:16.000
<Test>Valid
00:16.000 --> 00:8.000
<Test>This one should be ignored because the time is missing a digit.
''';
| plugins/packages/video_player/video_player/test/web_vtt_test.dart/0 | {
"file_path": "plugins/packages/video_player/video_player/test/web_vtt_test.dart",
"repo_id": "plugins",
"token_count": 2691
} | 1,342 |
// Copyright 2013 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.
package io.flutter.plugins.videoplayer;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.Format;
import io.flutter.plugin.common.EventChannel;
import io.flutter.view.TextureRegistry;
import java.util.HashMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class VideoPlayerTest {
private ExoPlayer fakeExoPlayer;
private EventChannel fakeEventChannel;
private TextureRegistry.SurfaceTextureEntry fakeSurfaceTextureEntry;
private VideoPlayerOptions fakeVideoPlayerOptions;
private QueuingEventSink fakeEventSink;
@Captor private ArgumentCaptor<HashMap<String, Object>> eventCaptor;
@Before
public void before() {
MockitoAnnotations.openMocks(this);
fakeExoPlayer = mock(ExoPlayer.class);
fakeEventChannel = mock(EventChannel.class);
fakeSurfaceTextureEntry = mock(TextureRegistry.SurfaceTextureEntry.class);
fakeVideoPlayerOptions = mock(VideoPlayerOptions.class);
fakeEventSink = mock(QueuingEventSink.class);
}
@Test
public void sendInitializedSendsExpectedEvent_90RotationDegrees() {
VideoPlayer videoPlayer =
new VideoPlayer(
fakeExoPlayer,
fakeEventChannel,
fakeSurfaceTextureEntry,
fakeVideoPlayerOptions,
fakeEventSink);
Format testFormat =
new Format.Builder().setWidth(100).setHeight(200).setRotationDegrees(90).build();
when(fakeExoPlayer.getVideoFormat()).thenReturn(testFormat);
when(fakeExoPlayer.getDuration()).thenReturn(10L);
videoPlayer.isInitialized = true;
videoPlayer.sendInitialized();
verify(fakeEventSink).success(eventCaptor.capture());
HashMap<String, Object> event = eventCaptor.getValue();
assertEquals(event.get("event"), "initialized");
assertEquals(event.get("duration"), 10L);
assertEquals(event.get("width"), 200);
assertEquals(event.get("height"), 100);
assertEquals(event.get("rotationCorrection"), null);
}
@Test
public void sendInitializedSendsExpectedEvent_270RotationDegrees() {
VideoPlayer videoPlayer =
new VideoPlayer(
fakeExoPlayer,
fakeEventChannel,
fakeSurfaceTextureEntry,
fakeVideoPlayerOptions,
fakeEventSink);
Format testFormat =
new Format.Builder().setWidth(100).setHeight(200).setRotationDegrees(270).build();
when(fakeExoPlayer.getVideoFormat()).thenReturn(testFormat);
when(fakeExoPlayer.getDuration()).thenReturn(10L);
videoPlayer.isInitialized = true;
videoPlayer.sendInitialized();
verify(fakeEventSink).success(eventCaptor.capture());
HashMap<String, Object> event = eventCaptor.getValue();
assertEquals(event.get("event"), "initialized");
assertEquals(event.get("duration"), 10L);
assertEquals(event.get("width"), 200);
assertEquals(event.get("height"), 100);
assertEquals(event.get("rotationCorrection"), null);
}
@Test
public void sendInitializedSendsExpectedEvent_0RotationDegrees() {
VideoPlayer videoPlayer =
new VideoPlayer(
fakeExoPlayer,
fakeEventChannel,
fakeSurfaceTextureEntry,
fakeVideoPlayerOptions,
fakeEventSink);
Format testFormat =
new Format.Builder().setWidth(100).setHeight(200).setRotationDegrees(0).build();
when(fakeExoPlayer.getVideoFormat()).thenReturn(testFormat);
when(fakeExoPlayer.getDuration()).thenReturn(10L);
videoPlayer.isInitialized = true;
videoPlayer.sendInitialized();
verify(fakeEventSink).success(eventCaptor.capture());
HashMap<String, Object> event = eventCaptor.getValue();
assertEquals(event.get("event"), "initialized");
assertEquals(event.get("duration"), 10L);
assertEquals(event.get("width"), 100);
assertEquals(event.get("height"), 200);
assertEquals(event.get("rotationCorrection"), null);
}
@Test
public void sendInitializedSendsExpectedEvent_180RotationDegrees() {
VideoPlayer videoPlayer =
new VideoPlayer(
fakeExoPlayer,
fakeEventChannel,
fakeSurfaceTextureEntry,
fakeVideoPlayerOptions,
fakeEventSink);
Format testFormat =
new Format.Builder().setWidth(100).setHeight(200).setRotationDegrees(180).build();
when(fakeExoPlayer.getVideoFormat()).thenReturn(testFormat);
when(fakeExoPlayer.getDuration()).thenReturn(10L);
videoPlayer.isInitialized = true;
videoPlayer.sendInitialized();
verify(fakeEventSink).success(eventCaptor.capture());
HashMap<String, Object> event = eventCaptor.getValue();
assertEquals(event.get("event"), "initialized");
assertEquals(event.get("duration"), 10L);
assertEquals(event.get("width"), 100);
assertEquals(event.get("height"), 200);
assertEquals(event.get("rotationCorrection"), 180);
}
}
| plugins/packages/video_player/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerTest.java/0 | {
"file_path": "plugins/packages/video_player/video_player_android/android/src/test/java/io/flutter/plugins/videoplayer/VideoPlayerTest.java",
"repo_id": "plugins",
"token_count": 1954
} | 1,343 |
// Copyright 2013 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.
// Autogenerated from Pigeon (v2.0.1), do not edit directly.
// See also: https://pub.dev/packages/pigeon
#import <Foundation/Foundation.h>
@protocol FlutterBinaryMessenger;
@protocol FlutterMessageCodec;
@class FlutterError;
@class FlutterStandardTypedData;
NS_ASSUME_NONNULL_BEGIN
@class FLTTextureMessage;
@class FLTLoopingMessage;
@class FLTVolumeMessage;
@class FLTPlaybackSpeedMessage;
@class FLTPositionMessage;
@class FLTCreateMessage;
@class FLTMixWithOthersMessage;
@interface FLTTextureMessage : NSObject
/// `init` unavailable to enforce nonnull fields, see the `make` class method.
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)makeWithTextureId:(NSNumber *)textureId;
@property(nonatomic, strong) NSNumber *textureId;
@end
@interface FLTLoopingMessage : NSObject
/// `init` unavailable to enforce nonnull fields, see the `make` class method.
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)makeWithTextureId:(NSNumber *)textureId isLooping:(NSNumber *)isLooping;
@property(nonatomic, strong) NSNumber *textureId;
@property(nonatomic, strong) NSNumber *isLooping;
@end
@interface FLTVolumeMessage : NSObject
/// `init` unavailable to enforce nonnull fields, see the `make` class method.
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)makeWithTextureId:(NSNumber *)textureId volume:(NSNumber *)volume;
@property(nonatomic, strong) NSNumber *textureId;
@property(nonatomic, strong) NSNumber *volume;
@end
@interface FLTPlaybackSpeedMessage : NSObject
/// `init` unavailable to enforce nonnull fields, see the `make` class method.
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)makeWithTextureId:(NSNumber *)textureId speed:(NSNumber *)speed;
@property(nonatomic, strong) NSNumber *textureId;
@property(nonatomic, strong) NSNumber *speed;
@end
@interface FLTPositionMessage : NSObject
/// `init` unavailable to enforce nonnull fields, see the `make` class method.
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)makeWithTextureId:(NSNumber *)textureId position:(NSNumber *)position;
@property(nonatomic, strong) NSNumber *textureId;
@property(nonatomic, strong) NSNumber *position;
@end
@interface FLTCreateMessage : NSObject
/// `init` unavailable to enforce nonnull fields, see the `make` class method.
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)makeWithAsset:(nullable NSString *)asset
uri:(nullable NSString *)uri
packageName:(nullable NSString *)packageName
formatHint:(nullable NSString *)formatHint
httpHeaders:(NSDictionary<NSString *, NSString *> *)httpHeaders;
@property(nonatomic, copy, nullable) NSString *asset;
@property(nonatomic, copy, nullable) NSString *uri;
@property(nonatomic, copy, nullable) NSString *packageName;
@property(nonatomic, copy, nullable) NSString *formatHint;
@property(nonatomic, strong) NSDictionary<NSString *, NSString *> *httpHeaders;
@end
@interface FLTMixWithOthersMessage : NSObject
/// `init` unavailable to enforce nonnull fields, see the `make` class method.
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)makeWithMixWithOthers:(NSNumber *)mixWithOthers;
@property(nonatomic, strong) NSNumber *mixWithOthers;
@end
/// The codec used by FLTAVFoundationVideoPlayerApi.
NSObject<FlutterMessageCodec> *FLTAVFoundationVideoPlayerApiGetCodec(void);
@protocol FLTAVFoundationVideoPlayerApi
- (void)initialize:(FlutterError *_Nullable *_Nonnull)error;
/// @return `nil` only when `error != nil`.
- (nullable FLTTextureMessage *)create:(FLTCreateMessage *)msg
error:(FlutterError *_Nullable *_Nonnull)error;
- (void)dispose:(FLTTextureMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error;
- (void)setLooping:(FLTLoopingMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error;
- (void)setVolume:(FLTVolumeMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error;
- (void)setPlaybackSpeed:(FLTPlaybackSpeedMessage *)msg
error:(FlutterError *_Nullable *_Nonnull)error;
- (void)play:(FLTTextureMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error;
/// @return `nil` only when `error != nil`.
- (nullable FLTPositionMessage *)position:(FLTTextureMessage *)msg
error:(FlutterError *_Nullable *_Nonnull)error;
- (void)seekTo:(FLTPositionMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error;
- (void)pause:(FLTTextureMessage *)msg error:(FlutterError *_Nullable *_Nonnull)error;
- (void)setMixWithOthers:(FLTMixWithOthersMessage *)msg
error:(FlutterError *_Nullable *_Nonnull)error;
@end
extern void FLTAVFoundationVideoPlayerApiSetup(
id<FlutterBinaryMessenger> binaryMessenger,
NSObject<FLTAVFoundationVideoPlayerApi> *_Nullable api);
NS_ASSUME_NONNULL_END
| plugins/packages/video_player/video_player_avfoundation/ios/Classes/messages.g.h/0 | {
"file_path": "plugins/packages/video_player/video_player_avfoundation/ios/Classes/messages.g.h",
"repo_id": "plugins",
"token_count": 1717
} | 1,344 |
name: video_player_platform_interface
description: A common platform interface for the video_player plugin.
repository: https://github.com/flutter/plugins/tree/main/packages/video_player/video_player_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+video_player%22
# NOTE: We strongly prefer non-breaking changes, even at the expense of a
# less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes
version: 6.0.1
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.1.0
dev_dependencies:
flutter_test:
sdk: flutter
| plugins/packages/video_player/video_player_platform_interface/pubspec.yaml/0 | {
"file_path": "plugins/packages/video_player/video_player_platform_interface/pubspec.yaml",
"repo_id": "plugins",
"token_count": 251
} | 1,345 |
// Copyright 2013 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 XCTest;
@import os.log;
@interface FLTWebViewUITests : XCTestCase
@property(nonatomic, strong) XCUIApplication *app;
@end
@implementation FLTWebViewUITests
- (void)setUp {
self.continueAfterFailure = NO;
self.app = [[XCUIApplication alloc] init];
[self.app launch];
}
- (void)testUserAgent {
XCUIApplication *app = self.app;
XCUIElement *menu = app.buttons[@"Show menu"];
if (![menu waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find menu");
}
[menu tap];
XCUIElement *userAgent = app.buttons[@"Show user agent"];
if (![userAgent waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find Show user agent");
}
NSPredicate *userAgentPredicate =
[NSPredicate predicateWithFormat:@"label BEGINSWITH 'User Agent: Mozilla/5.0 (iPhone; '"];
XCUIElement *userAgentPopUp = [app.otherElements elementMatchingPredicate:userAgentPredicate];
XCTAssertFalse(userAgentPopUp.exists);
[userAgent tap];
if (![userAgentPopUp waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find user agent pop up");
}
}
- (void)testCache {
XCUIApplication *app = self.app;
XCUIElement *menu = app.buttons[@"Show menu"];
if (![menu waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find menu");
}
[menu tap];
XCUIElement *clearCache = app.buttons[@"Clear cache"];
if (![clearCache waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find Clear cache");
}
[clearCache tap];
[menu tap];
XCUIElement *listCache = app.buttons[@"List cache"];
if (![listCache waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find List cache");
}
[listCache tap];
XCUIElement *emptyCachePopup = app.otherElements[@"{\"cacheKeys\":[],\"localStorage\":{}}"];
if (![emptyCachePopup waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find empty cache pop up");
}
[menu tap];
XCUIElement *addCache = app.buttons[@"Add to cache"];
if (![addCache waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find Add to cache");
}
[addCache tap];
[menu tap];
if (![listCache waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find List cache");
}
[listCache tap];
XCUIElement *cachePopup =
app.otherElements[@"{\"cacheKeys\":[\"test_caches_entry\"],\"localStorage\":{\"test_"
@"localStorage\":\"dummy_entry\"}}"];
if (![cachePopup waitForExistenceWithTimeout:30.0]) {
os_log_error(OS_LOG_DEFAULT, "%@", app.debugDescription);
XCTFail(@"Failed due to not able to find cache pop up");
}
}
@end
| plugins/packages/webview_flutter/webview_flutter/example/ios/RunnerUITests/FLTWebViewUITests.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/example/ios/RunnerUITests/FLTWebViewUITests.m",
"repo_id": "plugins",
"token_count": 1299
} | 1,346 |
// Copyright 2013 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:typed_data';
import 'package:flutter/src/foundation/basic_types.dart';
import 'package:flutter/src/gestures/recognizer.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:webview_flutter/src/webview_flutter_legacy.dart';
import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart';
import 'webview_flutter_test.mocks.dart';
typedef VoidCallback = void Function();
@GenerateMocks(<Type>[WebViewPlatform, WebViewPlatformController])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late MockWebViewPlatform mockWebViewPlatform;
late MockWebViewPlatformController mockWebViewPlatformController;
late MockWebViewCookieManagerPlatform mockWebViewCookieManagerPlatform;
setUp(() {
mockWebViewPlatformController = MockWebViewPlatformController();
mockWebViewPlatform = MockWebViewPlatform();
mockWebViewCookieManagerPlatform = MockWebViewCookieManagerPlatform();
when(mockWebViewPlatform.build(
context: anyNamed('context'),
creationParams: anyNamed('creationParams'),
webViewPlatformCallbacksHandler:
anyNamed('webViewPlatformCallbacksHandler'),
javascriptChannelRegistry: anyNamed('javascriptChannelRegistry'),
onWebViewPlatformCreated: anyNamed('onWebViewPlatformCreated'),
gestureRecognizers: anyNamed('gestureRecognizers'),
)).thenAnswer((Invocation invocation) {
final WebViewPlatformCreatedCallback onWebViewPlatformCreated =
invocation.namedArguments[const Symbol('onWebViewPlatformCreated')]
as WebViewPlatformCreatedCallback;
return TestPlatformWebView(
mockWebViewPlatformController: mockWebViewPlatformController,
onWebViewPlatformCreated: onWebViewPlatformCreated,
);
});
WebView.platform = mockWebViewPlatform;
WebViewCookieManagerPlatform.instance = mockWebViewCookieManagerPlatform;
});
tearDown(() {
mockWebViewCookieManagerPlatform.reset();
});
testWidgets('Create WebView', (WidgetTester tester) async {
await tester.pumpWidget(const WebView());
});
testWidgets('Initial url', (WidgetTester tester) async {
await tester.pumpWidget(const WebView(initialUrl: 'https://youtube.com'));
final CreationParams params = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(params.initialUrl, 'https://youtube.com');
});
testWidgets('Javascript mode', (WidgetTester tester) async {
await tester.pumpWidget(const WebView(
javascriptMode: JavascriptMode.unrestricted,
));
final CreationParams unrestrictedparams = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(
unrestrictedparams.webSettings!.javascriptMode,
JavascriptMode.unrestricted,
);
await tester.pumpWidget(const WebView());
final CreationParams disabledparams = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(disabledparams.webSettings!.javascriptMode, JavascriptMode.disabled);
});
testWidgets('Load file', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
await controller!.loadFile('/test/path/index.html');
verify(mockWebViewPlatformController.loadFile(
'/test/path/index.html',
));
});
testWidgets('Load file with empty path', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
expect(() => controller!.loadFile(''), throwsAssertionError);
});
testWidgets('Load Flutter asset', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
await controller!.loadFlutterAsset('assets/index.html');
verify(mockWebViewPlatformController.loadFlutterAsset(
'assets/index.html',
));
});
testWidgets('Load Flutter asset with empty key', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
expect(() => controller!.loadFlutterAsset(''), throwsAssertionError);
});
testWidgets('Load HTML string without base URL', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
await controller!.loadHtmlString('<p>This is a test paragraph.</p>');
verify(mockWebViewPlatformController.loadHtmlString(
'<p>This is a test paragraph.</p>',
));
});
testWidgets('Load HTML string with base URL', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
await controller!.loadHtmlString(
'<p>This is a test paragraph.</p>',
baseUrl: 'https://flutter.dev',
);
verify(mockWebViewPlatformController.loadHtmlString(
'<p>This is a test paragraph.</p>',
baseUrl: 'https://flutter.dev',
));
});
testWidgets('Load HTML string with empty string',
(WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
expect(() => controller!.loadHtmlString(''), throwsAssertionError);
});
testWidgets('Load url', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
await controller!.loadUrl('https://flutter.io');
verify(mockWebViewPlatformController.loadUrl(
'https://flutter.io',
argThat(isNull),
));
});
testWidgets('Invalid urls', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
final CreationParams params = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(params.initialUrl, isNull);
expect(() => controller!.loadUrl(''), throwsA(anything));
expect(() => controller!.loadUrl('flutter.io'), throwsA(anything));
});
testWidgets('Headers in loadUrl', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
final Map<String, String> headers = <String, String>{
'CACHE-CONTROL': 'ABC'
};
await controller!.loadUrl('https://flutter.io', headers: headers);
verify(mockWebViewPlatformController.loadUrl(
'https://flutter.io',
<String, String>{'CACHE-CONTROL': 'ABC'},
));
});
testWidgets('loadRequest', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
final WebViewRequest req = WebViewRequest(
uri: Uri.parse('https://flutter.dev'),
method: WebViewRequestMethod.post,
headers: <String, String>{'foo': 'bar'},
body: Uint8List.fromList('Test Body'.codeUnits),
);
await controller!.loadRequest(req);
verify(mockWebViewPlatformController.loadRequest(req));
});
testWidgets('Clear Cache', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
await controller!.clearCache();
verify(mockWebViewPlatformController.clearCache());
});
testWidgets('Can go back', (WidgetTester tester) async {
when(mockWebViewPlatformController.canGoBack())
.thenAnswer((_) => Future<bool>.value(true));
WebViewController? controller;
await tester.pumpWidget(
WebView(
initialUrl: 'https://flutter.io',
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
expect(controller!.canGoBack(), completion(true));
});
testWidgets("Can't go forward", (WidgetTester tester) async {
when(mockWebViewPlatformController.canGoForward())
.thenAnswer((_) => Future<bool>.value(false));
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
expect(controller!.canGoForward(), completion(false));
});
testWidgets('Go back', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
initialUrl: 'https://youtube.com',
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
await controller!.goBack();
verify(mockWebViewPlatformController.goBack());
});
testWidgets('Go forward', (WidgetTester tester) async {
WebViewController? controller;
await tester.pumpWidget(
WebView(
initialUrl: 'https://youtube.com',
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
await controller!.goForward();
verify(mockWebViewPlatformController.goForward());
});
testWidgets('Current URL', (WidgetTester tester) async {
when(mockWebViewPlatformController.currentUrl())
.thenAnswer((_) => Future<String>.value('https://youtube.com'));
WebViewController? controller;
await tester.pumpWidget(
WebView(
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(controller, isNotNull);
expect(await controller!.currentUrl(), 'https://youtube.com');
});
testWidgets('Reload url', (WidgetTester tester) async {
late WebViewController controller;
await tester.pumpWidget(
WebView(
initialUrl: 'https://flutter.io',
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
await controller.reload();
verify(mockWebViewPlatformController.reload());
});
testWidgets('evaluate Javascript', (WidgetTester tester) async {
when(mockWebViewPlatformController.evaluateJavascript('fake js string'))
.thenAnswer((_) => Future<String>.value('fake js string'));
late WebViewController controller;
await tester.pumpWidget(
WebView(
initialUrl: 'https://flutter.io',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(
// ignore: deprecated_member_use_from_same_package
await controller.evaluateJavascript('fake js string'),
'fake js string',
reason: 'should get the argument');
});
testWidgets('evaluate Javascript with JavascriptMode disabled',
(WidgetTester tester) async {
late WebViewController controller;
await tester.pumpWidget(
WebView(
initialUrl: 'https://flutter.io',
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(
// ignore: deprecated_member_use_from_same_package
() => controller.evaluateJavascript('fake js string'),
throwsA(anything),
);
});
testWidgets('runJavaScript', (WidgetTester tester) async {
late WebViewController controller;
await tester.pumpWidget(
WebView(
initialUrl: 'https://flutter.io',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
await controller.runJavascript('fake js string');
verify(mockWebViewPlatformController.runJavascript('fake js string'));
});
testWidgets('runJavaScript with JavascriptMode disabled',
(WidgetTester tester) async {
late WebViewController controller;
await tester.pumpWidget(
WebView(
initialUrl: 'https://flutter.io',
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(
() => controller.runJavascript('fake js string'),
throwsA(anything),
);
});
testWidgets('runJavaScriptReturningResult', (WidgetTester tester) async {
when(mockWebViewPlatformController
.runJavascriptReturningResult('fake js string'))
.thenAnswer((_) => Future<String>.value('fake js string'));
late WebViewController controller;
await tester.pumpWidget(
WebView(
initialUrl: 'https://flutter.io',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(await controller.runJavascriptReturningResult('fake js string'),
'fake js string',
reason: 'should get the argument');
});
testWidgets('runJavaScriptReturningResult with JavascriptMode disabled',
(WidgetTester tester) async {
late WebViewController controller;
await tester.pumpWidget(
WebView(
initialUrl: 'https://flutter.io',
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
expect(
() => controller.runJavascriptReturningResult('fake js string'),
throwsA(anything),
);
});
testWidgets('Cookies can be cleared once', (WidgetTester tester) async {
await tester.pumpWidget(
const WebView(
initialUrl: 'https://flutter.io',
),
);
final CookieManager cookieManager = CookieManager();
final bool hasCookies = await cookieManager.clearCookies();
expect(hasCookies, true);
});
testWidgets('Cookies can be set', (WidgetTester tester) async {
const WebViewCookie cookie =
WebViewCookie(name: 'foo', value: 'bar', domain: 'flutter.dev');
await tester.pumpWidget(
const WebView(
initialUrl: 'https://flutter.io',
),
);
final CookieManager cookieManager = CookieManager();
await cookieManager.setCookie(cookie);
expect(mockWebViewCookieManagerPlatform.setCookieCalls,
<WebViewCookie>[cookie]);
});
testWidgets('Initial JavaScript channels', (WidgetTester tester) async {
await tester.pumpWidget(
WebView(
initialUrl: 'https://youtube.com',
javascriptChannels: <JavascriptChannel>{
JavascriptChannel(
name: 'Tts', onMessageReceived: (JavascriptMessage msg) {}),
JavascriptChannel(
name: 'Alarm', onMessageReceived: (JavascriptMessage msg) {}),
},
),
);
final CreationParams params = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(params.javascriptChannelNames,
unorderedEquals(<String>['Tts', 'Alarm']));
});
test('Only valid JavaScript channel names are allowed', () {
void noOp(JavascriptMessage msg) {}
JavascriptChannel(name: 'Tts1', onMessageReceived: noOp);
JavascriptChannel(name: '_Alarm', onMessageReceived: noOp);
JavascriptChannel(name: 'foo_bar_', onMessageReceived: noOp);
VoidCallback createChannel(String name) {
return () {
JavascriptChannel(name: name, onMessageReceived: noOp);
};
}
expect(createChannel('1Alarm'), throwsAssertionError);
expect(createChannel('foo.bar'), throwsAssertionError);
expect(createChannel(''), throwsAssertionError);
});
testWidgets('Unique JavaScript channel names are required',
(WidgetTester tester) async {
await tester.pumpWidget(
WebView(
initialUrl: 'https://youtube.com',
javascriptChannels: <JavascriptChannel>{
JavascriptChannel(
name: 'Alarm', onMessageReceived: (JavascriptMessage msg) {}),
JavascriptChannel(
name: 'Alarm', onMessageReceived: (JavascriptMessage msg) {}),
},
),
);
expect(tester.takeException(), isNot(null));
});
testWidgets('JavaScript channels update', (WidgetTester tester) async {
await tester.pumpWidget(
WebView(
initialUrl: 'https://youtube.com',
javascriptChannels: <JavascriptChannel>{
JavascriptChannel(
name: 'Tts', onMessageReceived: (JavascriptMessage msg) {}),
JavascriptChannel(
name: 'Alarm', onMessageReceived: (JavascriptMessage msg) {}),
},
),
);
await tester.pumpWidget(
WebView(
initialUrl: 'https://youtube.com',
javascriptChannels: <JavascriptChannel>{
JavascriptChannel(
name: 'Tts', onMessageReceived: (JavascriptMessage msg) {}),
JavascriptChannel(
name: 'Alarm2', onMessageReceived: (JavascriptMessage msg) {}),
JavascriptChannel(
name: 'Alarm3', onMessageReceived: (JavascriptMessage msg) {}),
},
),
);
final JavascriptChannelRegistry channelRegistry = captureBuildArgs(
mockWebViewPlatform,
javascriptChannelRegistry: true,
).first as JavascriptChannelRegistry;
expect(
channelRegistry.channels.keys,
unorderedEquals(<String>['Tts', 'Alarm2', 'Alarm3']),
);
});
testWidgets('Remove all JavaScript channels and then add',
(WidgetTester tester) async {
// This covers a specific bug we had where after updating javascriptChannels to null,
// updating it again with a subset of the previously registered channels fails as the
// widget's cache of current channel wasn't properly updated when updating javascriptChannels to
// null.
await tester.pumpWidget(
WebView(
initialUrl: 'https://youtube.com',
javascriptChannels: <JavascriptChannel>{
JavascriptChannel(
name: 'Tts', onMessageReceived: (JavascriptMessage msg) {}),
},
),
);
await tester.pumpWidget(
const WebView(
initialUrl: 'https://youtube.com',
),
);
await tester.pumpWidget(
WebView(
initialUrl: 'https://youtube.com',
javascriptChannels: <JavascriptChannel>{
JavascriptChannel(
name: 'Tts', onMessageReceived: (JavascriptMessage msg) {}),
},
),
);
final JavascriptChannelRegistry channelRegistry = captureBuildArgs(
mockWebViewPlatform,
javascriptChannelRegistry: true,
).last as JavascriptChannelRegistry;
expect(channelRegistry.channels.keys, unorderedEquals(<String>['Tts']));
});
testWidgets('JavaScript channel messages', (WidgetTester tester) async {
final List<String> ttsMessagesReceived = <String>[];
final List<String> alarmMessagesReceived = <String>[];
await tester.pumpWidget(
WebView(
initialUrl: 'https://youtube.com',
javascriptChannels: <JavascriptChannel>{
JavascriptChannel(
name: 'Tts',
onMessageReceived: (JavascriptMessage msg) {
ttsMessagesReceived.add(msg.message);
}),
JavascriptChannel(
name: 'Alarm',
onMessageReceived: (JavascriptMessage msg) {
alarmMessagesReceived.add(msg.message);
}),
},
),
);
final JavascriptChannelRegistry channelRegistry = captureBuildArgs(
mockWebViewPlatform,
javascriptChannelRegistry: true,
).single as JavascriptChannelRegistry;
expect(ttsMessagesReceived, isEmpty);
expect(alarmMessagesReceived, isEmpty);
channelRegistry.onJavascriptChannelMessage('Tts', 'Hello');
channelRegistry.onJavascriptChannelMessage('Tts', 'World');
expect(ttsMessagesReceived, <String>['Hello', 'World']);
});
group('$PageStartedCallback', () {
testWidgets('onPageStarted is not null', (WidgetTester tester) async {
String? returnedUrl;
await tester.pumpWidget(WebView(
initialUrl: 'https://youtube.com',
onPageStarted: (String url) {
returnedUrl = url;
},
));
final WebViewPlatformCallbacksHandler handler = captureBuildArgs(
mockWebViewPlatform,
webViewPlatformCallbacksHandler: true,
).single as WebViewPlatformCallbacksHandler;
handler.onPageStarted('https://youtube.com');
expect(returnedUrl, 'https://youtube.com');
});
testWidgets('onPageStarted is null', (WidgetTester tester) async {
await tester.pumpWidget(const WebView(
initialUrl: 'https://youtube.com',
));
final WebViewPlatformCallbacksHandler handler = captureBuildArgs(
mockWebViewPlatform,
webViewPlatformCallbacksHandler: true,
).single as WebViewPlatformCallbacksHandler;
// The platform side will always invoke a call for onPageStarted. This is
// to test that it does not crash on a null callback.
handler.onPageStarted('https://youtube.com');
});
testWidgets('onPageStarted changed', (WidgetTester tester) async {
String? returnedUrl;
await tester.pumpWidget(WebView(
initialUrl: 'https://youtube.com',
onPageStarted: (String url) {},
));
await tester.pumpWidget(WebView(
initialUrl: 'https://youtube.com',
onPageStarted: (String url) {
returnedUrl = url;
},
));
final WebViewPlatformCallbacksHandler handler = captureBuildArgs(
mockWebViewPlatform,
webViewPlatformCallbacksHandler: true,
).last as WebViewPlatformCallbacksHandler;
handler.onPageStarted('https://youtube.com');
expect(returnedUrl, 'https://youtube.com');
});
});
group('$PageFinishedCallback', () {
testWidgets('onPageFinished is not null', (WidgetTester tester) async {
String? returnedUrl;
await tester.pumpWidget(WebView(
initialUrl: 'https://youtube.com',
onPageFinished: (String url) {
returnedUrl = url;
},
));
final WebViewPlatformCallbacksHandler handler = captureBuildArgs(
mockWebViewPlatform,
webViewPlatformCallbacksHandler: true,
).single as WebViewPlatformCallbacksHandler;
handler.onPageFinished('https://youtube.com');
expect(returnedUrl, 'https://youtube.com');
});
testWidgets('onPageFinished is null', (WidgetTester tester) async {
await tester.pumpWidget(const WebView(
initialUrl: 'https://youtube.com',
));
final WebViewPlatformCallbacksHandler handler = captureBuildArgs(
mockWebViewPlatform,
webViewPlatformCallbacksHandler: true,
).single as WebViewPlatformCallbacksHandler;
// The platform side will always invoke a call for onPageFinished. This is
// to test that it does not crash on a null callback.
handler.onPageFinished('https://youtube.com');
});
testWidgets('onPageFinished changed', (WidgetTester tester) async {
String? returnedUrl;
await tester.pumpWidget(WebView(
initialUrl: 'https://youtube.com',
onPageFinished: (String url) {},
));
await tester.pumpWidget(WebView(
initialUrl: 'https://youtube.com',
onPageFinished: (String url) {
returnedUrl = url;
},
));
final WebViewPlatformCallbacksHandler handler = captureBuildArgs(
mockWebViewPlatform,
webViewPlatformCallbacksHandler: true,
).last as WebViewPlatformCallbacksHandler;
handler.onPageFinished('https://youtube.com');
expect(returnedUrl, 'https://youtube.com');
});
});
group('$PageLoadingCallback', () {
testWidgets('onLoadingProgress is not null', (WidgetTester tester) async {
int? loadingProgress;
await tester.pumpWidget(WebView(
initialUrl: 'https://youtube.com',
onProgress: (int progress) {
loadingProgress = progress;
},
));
final WebViewPlatformCallbacksHandler handler = captureBuildArgs(
mockWebViewPlatform,
webViewPlatformCallbacksHandler: true,
).single as WebViewPlatformCallbacksHandler;
handler.onProgress(50);
expect(loadingProgress, 50);
});
testWidgets('onLoadingProgress is null', (WidgetTester tester) async {
await tester.pumpWidget(const WebView(
initialUrl: 'https://youtube.com',
));
final WebViewPlatformCallbacksHandler handler = captureBuildArgs(
mockWebViewPlatform,
webViewPlatformCallbacksHandler: true,
).single as WebViewPlatformCallbacksHandler;
// This is to test that it does not crash on a null callback.
handler.onProgress(50);
});
testWidgets('onLoadingProgress changed', (WidgetTester tester) async {
int? loadingProgress;
await tester.pumpWidget(WebView(
initialUrl: 'https://youtube.com',
onProgress: (int progress) {},
));
await tester.pumpWidget(WebView(
initialUrl: 'https://youtube.com',
onProgress: (int progress) {
loadingProgress = progress;
},
));
final WebViewPlatformCallbacksHandler handler = captureBuildArgs(
mockWebViewPlatform,
webViewPlatformCallbacksHandler: true,
).last as WebViewPlatformCallbacksHandler;
handler.onProgress(50);
expect(loadingProgress, 50);
});
});
group('navigationDelegate', () {
testWidgets('hasNavigationDelegate', (WidgetTester tester) async {
await tester.pumpWidget(const WebView(
initialUrl: 'https://youtube.com',
));
final CreationParams params = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(params.webSettings!.hasNavigationDelegate, false);
await tester.pumpWidget(WebView(
initialUrl: 'https://youtube.com',
navigationDelegate: (NavigationRequest r) =>
NavigationDecision.navigate,
));
final WebSettings updateSettings =
verify(mockWebViewPlatformController.updateSettings(captureAny))
.captured
.single as WebSettings;
expect(updateSettings.hasNavigationDelegate, true);
});
testWidgets('Block navigation', (WidgetTester tester) async {
final List<NavigationRequest> navigationRequests = <NavigationRequest>[];
await tester.pumpWidget(WebView(
initialUrl: 'https://youtube.com',
navigationDelegate: (NavigationRequest request) {
navigationRequests.add(request);
// Only allow navigating to https://flutter.dev
return request.url == 'https://flutter.dev'
? NavigationDecision.navigate
: NavigationDecision.prevent;
}));
final List<dynamic> args = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
webViewPlatformCallbacksHandler: true,
);
final CreationParams params = args[0] as CreationParams;
expect(params.webSettings!.hasNavigationDelegate, true);
final WebViewPlatformCallbacksHandler handler =
args[1] as WebViewPlatformCallbacksHandler;
// The navigation delegate only allows navigation to https://flutter.dev
// so we should still be in https://youtube.com.
expect(
handler.onNavigationRequest(
url: 'https://www.google.com',
isForMainFrame: true,
),
completion(false),
);
expect(navigationRequests.length, 1);
expect(navigationRequests[0].url, 'https://www.google.com');
expect(navigationRequests[0].isForMainFrame, true);
expect(
handler.onNavigationRequest(
url: 'https://flutter.dev',
isForMainFrame: true,
),
completion(true),
);
});
});
group('debuggingEnabled', () {
testWidgets('enable debugging', (WidgetTester tester) async {
await tester.pumpWidget(const WebView(
debuggingEnabled: true,
));
final CreationParams params = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(params.webSettings!.debuggingEnabled, true);
});
testWidgets('defaults to false', (WidgetTester tester) async {
await tester.pumpWidget(const WebView());
final CreationParams params = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(params.webSettings!.debuggingEnabled, false);
});
testWidgets('can be changed', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(WebView(key: key));
await tester.pumpWidget(WebView(
key: key,
debuggingEnabled: true,
));
final WebSettings enabledSettings =
verify(mockWebViewPlatformController.updateSettings(captureAny))
.captured
.last as WebSettings;
expect(enabledSettings.debuggingEnabled, true);
await tester.pumpWidget(WebView(
key: key,
));
final WebSettings disabledSettings =
verify(mockWebViewPlatformController.updateSettings(captureAny))
.captured
.last as WebSettings;
expect(disabledSettings.debuggingEnabled, false);
});
});
group('zoomEnabled', () {
testWidgets('Enable zoom', (WidgetTester tester) async {
await tester.pumpWidget(const WebView());
final CreationParams params = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(params.webSettings!.zoomEnabled, isTrue);
});
testWidgets('defaults to true', (WidgetTester tester) async {
await tester.pumpWidget(const WebView());
final CreationParams params = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(params.webSettings!.zoomEnabled, isTrue);
});
testWidgets('can be changed', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(WebView(key: key));
await tester.pumpWidget(WebView(
key: key,
));
final WebSettings enabledSettings =
verify(mockWebViewPlatformController.updateSettings(captureAny))
.captured
.last as WebSettings;
// Zoom defaults to true, so no changes are made to settings.
expect(enabledSettings.zoomEnabled, isNull);
await tester.pumpWidget(WebView(
key: key,
zoomEnabled: false,
));
final WebSettings disabledSettings =
verify(mockWebViewPlatformController.updateSettings(captureAny))
.captured
.last as WebSettings;
expect(disabledSettings.zoomEnabled, isFalse);
});
});
group('Background color', () {
testWidgets('Defaults to null', (WidgetTester tester) async {
await tester.pumpWidget(const WebView());
final CreationParams params = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(params.backgroundColor, null);
});
testWidgets('Can be transparent', (WidgetTester tester) async {
const Color transparentColor = Color(0x00000000);
await tester.pumpWidget(const WebView(
backgroundColor: transparentColor,
));
final CreationParams params = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(params.backgroundColor, transparentColor);
});
});
group('Custom platform implementation', () {
setUp(() {
WebView.platform = MyWebViewPlatform();
});
tearDownAll(() {
WebView.platform = null;
});
testWidgets('creation', (WidgetTester tester) async {
await tester.pumpWidget(
const WebView(
initialUrl: 'https://youtube.com',
gestureNavigationEnabled: true,
),
);
final MyWebViewPlatform builder = WebView.platform as MyWebViewPlatform;
final MyWebViewPlatformController platform = builder.lastPlatformBuilt!;
expect(
platform.creationParams,
MatchesCreationParams(CreationParams(
initialUrl: 'https://youtube.com',
webSettings: WebSettings(
javascriptMode: JavascriptMode.disabled,
hasNavigationDelegate: false,
debuggingEnabled: false,
userAgent: const WebSetting<String?>.of(null),
gestureNavigationEnabled: true,
zoomEnabled: true,
),
)));
});
testWidgets('loadUrl', (WidgetTester tester) async {
late WebViewController controller;
await tester.pumpWidget(
WebView(
initialUrl: 'https://youtube.com',
onWebViewCreated: (WebViewController webViewController) {
controller = webViewController;
},
),
);
final MyWebViewPlatform builder = WebView.platform as MyWebViewPlatform;
final MyWebViewPlatformController platform = builder.lastPlatformBuilt!;
final Map<String, String> headers = <String, String>{
'header': 'value',
};
await controller.loadUrl('https://google.com', headers: headers);
expect(platform.lastUrlLoaded, 'https://google.com');
expect(platform.lastRequestHeaders, headers);
});
});
testWidgets('Set UserAgent', (WidgetTester tester) async {
await tester.pumpWidget(const WebView(
initialUrl: 'https://youtube.com',
javascriptMode: JavascriptMode.unrestricted,
));
final CreationParams params = captureBuildArgs(
mockWebViewPlatform,
creationParams: true,
).single as CreationParams;
expect(params.webSettings!.userAgent.value, isNull);
await tester.pumpWidget(const WebView(
initialUrl: 'https://youtube.com',
javascriptMode: JavascriptMode.unrestricted,
userAgent: 'UA',
));
final WebSettings settings =
verify(mockWebViewPlatformController.updateSettings(captureAny))
.captured
.last as WebSettings;
expect(settings.userAgent.value, 'UA');
});
}
List<dynamic> captureBuildArgs(
MockWebViewPlatform mockWebViewPlatform, {
bool context = false,
bool creationParams = false,
bool webViewPlatformCallbacksHandler = false,
bool javascriptChannelRegistry = false,
bool onWebViewPlatformCreated = false,
bool gestureRecognizers = false,
}) {
return verify(mockWebViewPlatform.build(
context: context ? captureAnyNamed('context') : anyNamed('context'),
creationParams: creationParams
? captureAnyNamed('creationParams')
: anyNamed('creationParams'),
webViewPlatformCallbacksHandler: webViewPlatformCallbacksHandler
? captureAnyNamed('webViewPlatformCallbacksHandler')
: anyNamed('webViewPlatformCallbacksHandler'),
javascriptChannelRegistry: javascriptChannelRegistry
? captureAnyNamed('javascriptChannelRegistry')
: anyNamed('javascriptChannelRegistry'),
onWebViewPlatformCreated: onWebViewPlatformCreated
? captureAnyNamed('onWebViewPlatformCreated')
: anyNamed('onWebViewPlatformCreated'),
gestureRecognizers: gestureRecognizers
? captureAnyNamed('gestureRecognizers')
: anyNamed('gestureRecognizers'),
)).captured;
}
// This Widget ensures that onWebViewPlatformCreated is only called once when
// making multiple calls to `WidgetTester.pumpWidget` with different parameters
// for the WebView.
class TestPlatformWebView extends StatefulWidget {
const TestPlatformWebView({
super.key,
required this.mockWebViewPlatformController,
this.onWebViewPlatformCreated,
});
final MockWebViewPlatformController mockWebViewPlatformController;
final WebViewPlatformCreatedCallback? onWebViewPlatformCreated;
@override
State<StatefulWidget> createState() => TestPlatformWebViewState();
}
class TestPlatformWebViewState extends State<TestPlatformWebView> {
@override
void initState() {
super.initState();
final WebViewPlatformCreatedCallback? onWebViewPlatformCreated =
widget.onWebViewPlatformCreated;
if (onWebViewPlatformCreated != null) {
onWebViewPlatformCreated(widget.mockWebViewPlatformController);
}
}
@override
Widget build(BuildContext context) {
return Container();
}
}
class MyWebViewPlatform implements WebViewPlatform {
MyWebViewPlatformController? lastPlatformBuilt;
@override
Widget build({
BuildContext? context,
CreationParams? creationParams,
required WebViewPlatformCallbacksHandler webViewPlatformCallbacksHandler,
required JavascriptChannelRegistry javascriptChannelRegistry,
WebViewPlatformCreatedCallback? onWebViewPlatformCreated,
Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers,
}) {
assert(onWebViewPlatformCreated != null);
lastPlatformBuilt = MyWebViewPlatformController(
creationParams, gestureRecognizers, webViewPlatformCallbacksHandler);
onWebViewPlatformCreated!(lastPlatformBuilt);
return Container();
}
@override
Future<bool> clearCookies() {
return Future<bool>.sync(() => true);
}
}
class MyWebViewPlatformController extends WebViewPlatformController {
MyWebViewPlatformController(this.creationParams, this.gestureRecognizers,
WebViewPlatformCallbacksHandler platformHandler)
: super(platformHandler);
CreationParams? creationParams;
Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers;
String? lastUrlLoaded;
Map<String, String>? lastRequestHeaders;
@override
Future<void> loadUrl(String url, Map<String, String>? headers) async {
equals(1, 1);
lastUrlLoaded = url;
lastRequestHeaders = headers;
}
}
class MatchesWebSettings extends Matcher {
MatchesWebSettings(this._webSettings);
final WebSettings? _webSettings;
@override
Description describe(Description description) =>
description.add('$_webSettings');
@override
bool matches(
covariant WebSettings webSettings, Map<dynamic, dynamic> matchState) {
return _webSettings!.javascriptMode == webSettings.javascriptMode &&
_webSettings!.hasNavigationDelegate ==
webSettings.hasNavigationDelegate &&
_webSettings!.debuggingEnabled == webSettings.debuggingEnabled &&
_webSettings!.gestureNavigationEnabled ==
webSettings.gestureNavigationEnabled &&
_webSettings!.userAgent == webSettings.userAgent &&
_webSettings!.zoomEnabled == webSettings.zoomEnabled;
}
}
class MatchesCreationParams extends Matcher {
MatchesCreationParams(this._creationParams);
final CreationParams _creationParams;
@override
Description describe(Description description) =>
description.add('$_creationParams');
@override
bool matches(covariant CreationParams creationParams,
Map<dynamic, dynamic> matchState) {
return _creationParams.initialUrl == creationParams.initialUrl &&
MatchesWebSettings(_creationParams.webSettings)
.matches(creationParams.webSettings!, matchState) &&
orderedEquals(_creationParams.javascriptChannelNames)
.matches(creationParams.javascriptChannelNames, matchState);
}
}
class MockWebViewCookieManagerPlatform extends WebViewCookieManagerPlatform {
List<WebViewCookie> setCookieCalls = <WebViewCookie>[];
@override
Future<bool> clearCookies() async => true;
@override
Future<void> setCookie(WebViewCookie cookie) async {
setCookieCalls.add(cookie);
}
void reset() {
setCookieCalls = <WebViewCookie>[];
}
}
| plugins/packages/webview_flutter/webview_flutter/test/legacy/webview_flutter_test.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter/test/legacy/webview_flutter_test.dart",
"repo_id": "plugins",
"token_count": 15703
} | 1,347 |
rootProject.name = 'webview_flutter'
| plugins/packages/webview_flutter/webview_flutter_android/android/settings.gradle/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/settings.gradle",
"repo_id": "plugins",
"token_count": 13
} | 1,348 |
// Copyright 2013 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.
package io.flutter.plugins.webviewflutter;
import android.os.Handler;
import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.JavaScriptChannelHostApi;
/**
* Host api implementation for {@link JavaScriptChannel}.
*
* <p>Handles creating {@link JavaScriptChannel}s that intercommunicate with a paired Dart object.
*/
public class JavaScriptChannelHostApiImpl implements JavaScriptChannelHostApi {
private final InstanceManager instanceManager;
private final JavaScriptChannelCreator javaScriptChannelCreator;
private final JavaScriptChannelFlutterApiImpl flutterApi;
private Handler platformThreadHandler;
/** Handles creating {@link JavaScriptChannel}s for a {@link JavaScriptChannelHostApiImpl}. */
public static class JavaScriptChannelCreator {
/**
* Creates a {@link JavaScriptChannel}.
*
* @param flutterApi handles sending messages to Dart
* @param channelName JavaScript channel the message should be sent through
* @param platformThreadHandler handles making callbacks on the desired thread
* @return the created {@link JavaScriptChannel}
*/
public JavaScriptChannel createJavaScriptChannel(
JavaScriptChannelFlutterApiImpl flutterApi,
String channelName,
Handler platformThreadHandler) {
return new JavaScriptChannel(flutterApi, channelName, platformThreadHandler);
}
}
/**
* Creates a host API that handles creating {@link JavaScriptChannel}s.
*
* @param instanceManager maintains instances stored to communicate with Dart objects
* @param javaScriptChannelCreator handles creating {@link JavaScriptChannel}s
* @param flutterApi handles sending messages to Dart
* @param platformThreadHandler handles making callbacks on the desired thread
*/
public JavaScriptChannelHostApiImpl(
InstanceManager instanceManager,
JavaScriptChannelCreator javaScriptChannelCreator,
JavaScriptChannelFlutterApiImpl flutterApi,
Handler platformThreadHandler) {
this.instanceManager = instanceManager;
this.javaScriptChannelCreator = javaScriptChannelCreator;
this.flutterApi = flutterApi;
this.platformThreadHandler = platformThreadHandler;
}
/**
* Sets the platformThreadHandler to make callbacks
*
* @param platformThreadHandler the new thread handler
*/
public void setPlatformThreadHandler(Handler platformThreadHandler) {
this.platformThreadHandler = platformThreadHandler;
}
@Override
public void create(Long instanceId, String channelName) {
final JavaScriptChannel javaScriptChannel =
javaScriptChannelCreator.createJavaScriptChannel(
flutterApi, channelName, platformThreadHandler);
instanceManager.addDartCreatedInstance(javaScriptChannel, instanceId);
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/JavaScriptChannelHostApiImpl.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/JavaScriptChannelHostApiImpl.java",
"repo_id": "plugins",
"token_count": 824
} | 1,349 |
// Copyright 2013 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.
package io.flutter.plugins.webviewflutter;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import android.content.Context;
import android.view.View;
import org.junit.Test;
public class InputAwareWebViewTest {
static class TestView extends View {
Runnable postAction;
public TestView(Context context) {
super(context);
}
@Override
public boolean post(Runnable action) {
postAction = action;
return true;
}
}
@Test
public void runnableChecksContainerViewIsNull() {
final Context mockContext = mock(Context.class);
final TestView containerView = new TestView(mockContext);
final InputAwareWebView inputAwareWebView = new InputAwareWebView(mockContext, containerView);
final View mockProxyAdapterView = mock(View.class);
inputAwareWebView.setInputConnectionTarget(mockProxyAdapterView);
inputAwareWebView.setContainerView(null);
assertNotNull(containerView.postAction);
containerView.postAction.run();
verify(mockProxyAdapterView, never()).onWindowFocusChanged(anyBoolean());
}
}
| plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/InputAwareWebViewTest.java/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/InputAwareWebViewTest.java",
"repo_id": "plugins",
"token_count": 459
} | 1,350 |
// Copyright 2013 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 'android_webview.dart' as android_webview;
/// Handles constructing objects and calling static methods for the Android
/// WebView native library.
///
/// This class provides dependency injection for the implementations of the
/// platform interface classes. Improving the ease of unit testing and/or
/// overriding the underlying Android WebView classes.
///
/// By default each function calls the default constructor of the WebView class
/// it intends to return.
class AndroidWebViewProxy {
/// Constructs a [AndroidWebViewProxy].
const AndroidWebViewProxy({
this.createAndroidWebView = android_webview.WebView.new,
this.createAndroidWebChromeClient = android_webview.WebChromeClient.new,
this.createAndroidWebViewClient = android_webview.WebViewClient.new,
this.createFlutterAssetManager = android_webview.FlutterAssetManager.new,
this.createJavaScriptChannel = android_webview.JavaScriptChannel.new,
this.createDownloadListener = android_webview.DownloadListener.new,
});
/// Constructs a [android_webview.WebView].
///
/// Due to changes in Flutter 3.0 the [useHybridComposition] doesn't have
/// any effect and should not be exposed publicly. More info here:
/// https://github.com/flutter/flutter/issues/108106
final android_webview.WebView Function({
required bool useHybridComposition,
}) createAndroidWebView;
/// Constructs a [android_webview.WebChromeClient].
final android_webview.WebChromeClient Function({
void Function(android_webview.WebView webView, int progress)?
onProgressChanged,
Future<List<String>> Function(
android_webview.WebView webView,
android_webview.FileChooserParams params,
)?
onShowFileChooser,
}) createAndroidWebChromeClient;
/// Constructs a [android_webview.WebViewClient].
final android_webview.WebViewClient Function({
void Function(android_webview.WebView webView, String url)? onPageStarted,
void Function(android_webview.WebView webView, String url)? onPageFinished,
void Function(
android_webview.WebView webView,
android_webview.WebResourceRequest request,
android_webview.WebResourceError error,
)?
onReceivedRequestError,
@Deprecated('Only called on Android version < 23.')
void Function(
android_webview.WebView webView,
int errorCode,
String description,
String failingUrl,
)?
onReceivedError,
void Function(
android_webview.WebView webView,
android_webview.WebResourceRequest request,
)?
requestLoading,
void Function(android_webview.WebView webView, String url)? urlLoading,
}) createAndroidWebViewClient;
/// Constructs a [android_webview.FlutterAssetManager].
final android_webview.FlutterAssetManager Function()
createFlutterAssetManager;
/// Constructs a [android_webview.JavaScriptChannel].
final android_webview.JavaScriptChannel Function(
String channelName, {
required void Function(String) postMessage,
}) createJavaScriptChannel;
/// Constructs a [android_webview.DownloadListener].
final android_webview.DownloadListener Function({
required void Function(
String url,
String userAgent,
String contentDisposition,
String mimetype,
int contentLength,
)
onDownloadStart,
}) createDownloadListener;
/// Enables debugging of web contents (HTML / CSS / JavaScript) loaded into any WebViews of this application.
///
/// This flag can be enabled in order to facilitate debugging of web layouts
/// and JavaScript code running inside WebViews. Please refer to
/// [android_webview.WebView] documentation for the debugging guide. The
/// default is false.
///
/// See [android_webview.WebView].setWebContentsDebuggingEnabled.
Future<void> setWebContentsDebuggingEnabled(bool enabled) {
return android_webview.WebView.setWebContentsDebuggingEnabled(enabled);
}
}
| plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_proxy.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/lib/src/android_proxy.dart",
"repo_id": "plugins",
"token_count": 1259
} | 1,351 |
// Copyright 2013 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:pigeon/pigeon.dart';
@ConfigurePigeon(
PigeonOptions(
dartOut: 'lib/src/android_webview.g.dart',
dartTestOut: 'test/test_android_webview.g.dart',
dartOptions: DartOptions(copyrightHeader: <String>[
'Copyright 2013 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.',
]),
javaOut:
'android/src/main/java/io/flutter/plugins/webviewflutter/GeneratedAndroidWebView.java',
javaOptions: JavaOptions(
package: 'io.flutter.plugins.webviewflutter',
className: 'GeneratedAndroidWebView',
copyrightHeader: <String>[
'Copyright 2013 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.',
],
),
),
)
/// Mode of how to select files for a file chooser.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams.
enum FileChooserMode {
/// Open single file and requires that the file exists before allowing the
/// user to pick it.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_OPEN.
open,
/// Similar to [open] but allows multiple files to be selected.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_OPEN_MULTIPLE.
openMultiple,
/// Allows picking a nonexistent file and saving it.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_SAVE.
save,
}
// TODO(bparrishMines): Enums need be wrapped in a data class because thay can't
// be used as primitive arguments. See https://github.com/flutter/flutter/issues/87307
class FileChooserModeEnumData {
late FileChooserMode value;
}
class WebResourceRequestData {
WebResourceRequestData(
this.url,
this.isForMainFrame,
this.isRedirect,
this.hasGesture,
this.method,
this.requestHeaders,
);
String url;
bool isForMainFrame;
bool? isRedirect;
bool hasGesture;
String method;
Map<String?, String?> requestHeaders;
}
class WebResourceErrorData {
WebResourceErrorData(this.errorCode, this.description);
int errorCode;
String description;
}
class WebViewPoint {
WebViewPoint(this.x, this.y);
int x;
int y;
}
/// Handles methods calls to the native Java Object class.
///
/// Also handles calls to remove the reference to an instance with `dispose`.
///
/// See https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html.
@HostApi(dartHostTestHandler: 'TestJavaObjectHostApi')
abstract class JavaObjectHostApi {
void dispose(int identifier);
}
/// Handles callbacks methods for the native Java Object class.
///
/// See https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html.
@FlutterApi()
abstract class JavaObjectFlutterApi {
void dispose(int identifier);
}
@HostApi()
abstract class CookieManagerHostApi {
@async
bool clearCookies();
void setCookie(String url, String value);
}
@HostApi(dartHostTestHandler: 'TestWebViewHostApi')
abstract class WebViewHostApi {
void create(int instanceId, bool useHybridComposition);
void loadData(
int instanceId,
String data,
String? mimeType,
String? encoding,
);
void loadDataWithBaseUrl(
int instanceId,
String? baseUrl,
String data,
String? mimeType,
String? encoding,
String? historyUrl,
);
void loadUrl(
int instanceId,
String url,
Map<String, String> headers,
);
void postUrl(
int instanceId,
String url,
Uint8List data,
);
String? getUrl(int instanceId);
bool canGoBack(int instanceId);
bool canGoForward(int instanceId);
void goBack(int instanceId);
void goForward(int instanceId);
void reload(int instanceId);
void clearCache(int instanceId, bool includeDiskFiles);
@async
String? evaluateJavascript(
int instanceId,
String javascriptString,
);
String? getTitle(int instanceId);
void scrollTo(int instanceId, int x, int y);
void scrollBy(int instanceId, int x, int y);
int getScrollX(int instanceId);
int getScrollY(int instanceId);
WebViewPoint getScrollPosition(int instanceId);
void setWebContentsDebuggingEnabled(bool enabled);
void setWebViewClient(int instanceId, int webViewClientInstanceId);
void addJavaScriptChannel(int instanceId, int javaScriptChannelInstanceId);
void removeJavaScriptChannel(int instanceId, int javaScriptChannelInstanceId);
void setDownloadListener(int instanceId, int? listenerInstanceId);
void setWebChromeClient(int instanceId, int? clientInstanceId);
void setBackgroundColor(int instanceId, int color);
}
@HostApi(dartHostTestHandler: 'TestWebSettingsHostApi')
abstract class WebSettingsHostApi {
void create(int instanceId, int webViewInstanceId);
void setDomStorageEnabled(int instanceId, bool flag);
void setJavaScriptCanOpenWindowsAutomatically(int instanceId, bool flag);
void setSupportMultipleWindows(int instanceId, bool support);
void setJavaScriptEnabled(int instanceId, bool flag);
void setUserAgentString(int instanceId, String? userAgentString);
void setMediaPlaybackRequiresUserGesture(int instanceId, bool require);
void setSupportZoom(int instanceId, bool support);
void setLoadWithOverviewMode(int instanceId, bool overview);
void setUseWideViewPort(int instanceId, bool use);
void setDisplayZoomControls(int instanceId, bool enabled);
void setBuiltInZoomControls(int instanceId, bool enabled);
void setAllowFileAccess(int instanceId, bool enabled);
}
@HostApi(dartHostTestHandler: 'TestJavaScriptChannelHostApi')
abstract class JavaScriptChannelHostApi {
void create(int instanceId, String channelName);
}
@FlutterApi()
abstract class JavaScriptChannelFlutterApi {
void postMessage(int instanceId, String message);
}
@HostApi(dartHostTestHandler: 'TestWebViewClientHostApi')
abstract class WebViewClientHostApi {
void create(int instanceId);
void setSynchronousReturnValueForShouldOverrideUrlLoading(
int instanceId,
bool value,
);
}
@FlutterApi()
abstract class WebViewClientFlutterApi {
void onPageStarted(int instanceId, int webViewInstanceId, String url);
void onPageFinished(int instanceId, int webViewInstanceId, String url);
void onReceivedRequestError(
int instanceId,
int webViewInstanceId,
WebResourceRequestData request,
WebResourceErrorData error,
);
void onReceivedError(
int instanceId,
int webViewInstanceId,
int errorCode,
String description,
String failingUrl,
);
void requestLoading(
int instanceId,
int webViewInstanceId,
WebResourceRequestData request,
);
void urlLoading(int instanceId, int webViewInstanceId, String url);
}
@HostApi(dartHostTestHandler: 'TestDownloadListenerHostApi')
abstract class DownloadListenerHostApi {
void create(int instanceId);
}
@FlutterApi()
abstract class DownloadListenerFlutterApi {
void onDownloadStart(
int instanceId,
String url,
String userAgent,
String contentDisposition,
String mimetype,
int contentLength,
);
}
@HostApi(dartHostTestHandler: 'TestWebChromeClientHostApi')
abstract class WebChromeClientHostApi {
void create(int instanceId);
void setSynchronousReturnValueForOnShowFileChooser(
int instanceId,
bool value,
);
}
@HostApi(dartHostTestHandler: 'TestAssetManagerHostApi')
abstract class FlutterAssetManagerHostApi {
List<String> list(String path);
String getAssetFilePathByName(String name);
}
@FlutterApi()
abstract class WebChromeClientFlutterApi {
void onProgressChanged(int instanceId, int webViewInstanceId, int progress);
@async
List<String> onShowFileChooser(
int instanceId,
int webViewInstanceId,
int paramsInstanceId,
);
}
@HostApi(dartHostTestHandler: 'TestWebStorageHostApi')
abstract class WebStorageHostApi {
void create(int instanceId);
void deleteAllData(int instanceId);
}
/// Handles callbacks methods for the native Java FileChooserParams class.
///
/// See https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams.
@FlutterApi()
abstract class FileChooserParamsFlutterApi {
void create(
int instanceId,
bool isCaptureEnabled,
List<String> acceptTypes,
FileChooserModeEnumData mode,
String? filenameHint,
);
}
| plugins/packages/webview_flutter/webview_flutter_android/pigeons/android_webview.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_android/pigeons/android_webview.dart",
"repo_id": "plugins",
"token_count": 2807
} | 1,352 |
// Copyright 2013 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 'web_resource_error_type.dart';
/// Error returned in `WebView.onWebResourceError` when a web resource loading error has occurred.
class WebResourceError {
/// Creates a new [WebResourceError]
///
/// A user should not need to instantiate this class, but will receive one in
/// [WebResourceErrorCallback].
WebResourceError({
required this.errorCode,
required this.description,
this.domain,
this.errorType,
this.failingUrl,
}) : assert(errorCode != null),
assert(description != null);
/// Raw code of the error from the respective platform.
///
/// On Android, the error code will be a constant from a
/// [WebViewClient](https://developer.android.com/reference/android/webkit/WebViewClient#summary) and
/// will have a corresponding [errorType].
///
/// On iOS, the error code will be a constant from `NSError.code` in
/// Objective-C. See
/// https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/ErrorObjectsDomains/ErrorObjectsDomains.html
/// for more information on error handling on iOS. Some possible error codes
/// can be found at https://developer.apple.com/documentation/webkit/wkerrorcode?language=objc.
final int errorCode;
/// The domain of where to find the error code.
///
/// This field is only available on iOS and represents a "domain" from where
/// the [errorCode] is from. This value is taken directly from an `NSError`
/// in Objective-C. See
/// https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/ErrorObjectsDomains/ErrorObjectsDomains.html
/// for more information on error handling on iOS.
final String? domain;
/// Description of the error that can be used to communicate the problem to the user.
final String description;
/// The type this error can be categorized as.
///
/// This will never be `null` on Android, but can be `null` on iOS.
final WebResourceErrorType? errorType;
/// Gets the URL for which the resource request was made.
///
/// This value is not provided on iOS. Alternatively, you can keep track of
/// the last values provided to [WebViewPlatformController.loadUrl].
final String? failingUrl;
}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/web_resource_error.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/web_resource_error.dart",
"repo_id": "plugins",
"token_count": 682
} | 1,353 |
// Copyright 2013 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/material.dart';
/// Object specifying creation parameters for creating a [PlatformWebViewCookieManager].
///
/// Platform specific implementations can add additional fields by extending
/// this class.
///
/// {@tool sample}
/// This example demonstrates how to extend the [PlatformWebViewCookieManagerCreationParams] to
/// provide additional platform specific parameters.
///
/// When extending [PlatformWebViewCookieManagerCreationParams] additional
/// parameters should always accept `null` or have a default value to prevent
/// breaking changes.
///
/// ```dart
/// class WKWebViewCookieManagerCreationParams
/// extends PlatformWebViewCookieManagerCreationParams {
/// WKWebViewCookieManagerCreationParams._(
/// // This parameter prevents breaking changes later.
/// // ignore: avoid_unused_constructor_parameters
/// PlatformWebViewCookieManagerCreationParams params, {
/// this.uri,
/// }) : super();
///
/// factory WKWebViewCookieManagerCreationParams.fromPlatformWebViewCookieManagerCreationParams(
/// PlatformWebViewCookieManagerCreationParams params, {
/// Uri? uri,
/// }) {
/// return WKWebViewCookieManagerCreationParams._(params, uri: uri);
/// }
///
/// final Uri? uri;
/// }
/// ```
/// {@end-tool}
@immutable
class PlatformWebViewCookieManagerCreationParams {
/// Used by the platform implementation to create a new [PlatformWebViewCookieManagerDelegate].
const PlatformWebViewCookieManagerCreationParams();
}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/platform_webview_cookie_manager_creation_params.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/platform_webview_cookie_manager_creation_params.dart",
"repo_id": "plugins",
"token_count": 479
} | 1,354 |
// Mocks generated by Mockito 5.3.2 from annotations
// in webview_flutter_platform_interface/test/platform_webview_controller_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'package:mockito/mockito.dart' as _i1;
import 'package:webview_flutter_platform_interface/src/platform_navigation_delegate.dart'
as _i3;
import 'package:webview_flutter_platform_interface/src/webview_platform.dart'
as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakePlatformNavigationDelegateCreationParams_0 extends _i1.SmartFake
implements _i2.PlatformNavigationDelegateCreationParams {
_FakePlatformNavigationDelegateCreationParams_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [PlatformNavigationDelegate].
///
/// See the documentation for Mockito's code generation for more information.
class MockPlatformNavigationDelegate extends _i1.Mock
implements _i3.PlatformNavigationDelegate {
MockPlatformNavigationDelegate() {
_i1.throwOnMissingStub(this);
}
@override
_i2.PlatformNavigationDelegateCreationParams get params =>
(super.noSuchMethod(
Invocation.getter(#params),
returnValue: _FakePlatformNavigationDelegateCreationParams_0(
this,
Invocation.getter(#params),
),
) as _i2.PlatformNavigationDelegateCreationParams);
@override
_i4.Future<void> setOnNavigationRequest(
_i3.NavigationRequestCallback? onNavigationRequest) =>
(super.noSuchMethod(
Invocation.method(
#setOnNavigationRequest,
[onNavigationRequest],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setOnPageStarted(_i3.PageEventCallback? onPageStarted) =>
(super.noSuchMethod(
Invocation.method(
#setOnPageStarted,
[onPageStarted],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setOnPageFinished(_i3.PageEventCallback? onPageFinished) =>
(super.noSuchMethod(
Invocation.method(
#setOnPageFinished,
[onPageFinished],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setOnProgress(_i3.ProgressCallback? onProgress) =>
(super.noSuchMethod(
Invocation.method(
#setOnProgress,
[onProgress],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setOnWebResourceError(
_i3.WebResourceErrorCallback? onWebResourceError) =>
(super.noSuchMethod(
Invocation.method(
#setOnWebResourceError,
[onWebResourceError],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
}
| plugins/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.mocks.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_platform_interface/test/platform_webview_controller_test.mocks.dart",
"repo_id": "plugins",
"token_count": 1520
} | 1,355 |
// Copyright 2013 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 Flutter;
@import XCTest;
@import webview_flutter_wkwebview;
#import <OCMock/OCMock.h>
@interface FWFScrollViewHostApiTests : XCTestCase
@end
@implementation FWFScrollViewHostApiTests
- (void)testGetContentOffset {
UIScrollView *mockScrollView = OCMClassMock([UIScrollView class]);
OCMStub([mockScrollView contentOffset]).andReturn(CGPointMake(1.0, 2.0));
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:mockScrollView withIdentifier:0];
FWFScrollViewHostApiImpl *hostAPI =
[[FWFScrollViewHostApiImpl alloc] initWithInstanceManager:instanceManager];
FlutterError *error;
NSArray<NSNumber *> *expectedValue = @[ @1.0, @2.0 ];
XCTAssertEqualObjects([hostAPI contentOffsetForScrollViewWithIdentifier:@0 error:&error],
expectedValue);
XCTAssertNil(error);
}
- (void)testScrollBy {
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)];
scrollView.contentOffset = CGPointMake(1, 2);
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:scrollView withIdentifier:0];
FWFScrollViewHostApiImpl *hostAPI =
[[FWFScrollViewHostApiImpl alloc] initWithInstanceManager:instanceManager];
FlutterError *error;
[hostAPI scrollByForScrollViewWithIdentifier:@0 x:@1 y:@2 error:&error];
XCTAssertEqual(scrollView.contentOffset.x, 2);
XCTAssertEqual(scrollView.contentOffset.y, 4);
XCTAssertNil(error);
}
- (void)testSetContentOffset {
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)];
FWFInstanceManager *instanceManager = [[FWFInstanceManager alloc] init];
[instanceManager addDartCreatedInstance:scrollView withIdentifier:0];
FWFScrollViewHostApiImpl *hostAPI =
[[FWFScrollViewHostApiImpl alloc] initWithInstanceManager:instanceManager];
FlutterError *error;
[hostAPI setContentOffsetForScrollViewWithIdentifier:@0 toX:@1 y:@2 error:&error];
XCTAssertEqual(scrollView.contentOffset.x, 1);
XCTAssertEqual(scrollView.contentOffset.y, 2);
XCTAssertNil(error);
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFScrollViewHostApiTests.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/FWFScrollViewHostApiTests.m",
"repo_id": "plugins",
"token_count": 810
} | 1,356 |
// Copyright 2013 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 "FWFObjectHostApi.h"
#import "FWFDataConverters.h"
@interface FWFObjectFlutterApiImpl ()
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFObjectFlutterApiImpl
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [self initWithBinaryMessenger:binaryMessenger];
if (self) {
_instanceManager = instanceManager;
}
return self;
}
- (long)identifierForObject:(NSObject *)instance {
return [self.instanceManager identifierWithStrongReferenceForInstance:instance];
}
- (void)observeValueForObject:(NSObject *)instance
keyPath:(NSString *)keyPath
object:(NSObject *)object
change:(NSDictionary<NSKeyValueChangeKey, id> *)change
completion:(void (^)(NSError *_Nullable))completion {
NSMutableArray<FWFNSKeyValueChangeKeyEnumData *> *changeKeys = [NSMutableArray array];
NSMutableArray<id> *changeValues = [NSMutableArray array];
[change enumerateKeysAndObjectsUsingBlock:^(NSKeyValueChangeKey key, id value, BOOL *stop) {
[changeKeys addObject:FWFNSKeyValueChangeKeyEnumDataFromNSKeyValueChangeKey(key)];
[changeValues addObject:value];
}];
NSNumber *objectIdentifier =
@([self.instanceManager identifierWithStrongReferenceForInstance:object]);
[self observeValueForObjectWithIdentifier:@([self identifierForObject:instance])
keyPath:keyPath
objectIdentifier:objectIdentifier
changeKeys:changeKeys
changeValues:changeValues
completion:completion];
}
@end
@implementation FWFObject
- (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger
instanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_objectApi = [[FWFObjectFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger
instanceManager:instanceManager];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSKeyValueChangeKey, id> *)change
context:(void *)context {
[self.objectApi observeValueForObject:self
keyPath:keyPath
object:object
change:change
completion:^(NSError *error) {
NSAssert(!error, @"%@", error);
}];
}
@end
@interface FWFObjectHostApiImpl ()
// InstanceManager must be weak to prevent a circular reference with the object it stores.
@property(nonatomic, weak) FWFInstanceManager *instanceManager;
@end
@implementation FWFObjectHostApiImpl
- (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager {
self = [self init];
if (self) {
_instanceManager = instanceManager;
}
return self;
}
- (NSObject *)objectForIdentifier:(NSNumber *)identifier {
return (NSObject *)[self.instanceManager instanceForIdentifier:identifier.longValue];
}
- (void)addObserverForObjectWithIdentifier:(nonnull NSNumber *)identifier
observerIdentifier:(nonnull NSNumber *)observer
keyPath:(nonnull NSString *)keyPath
options:
(nonnull NSArray<FWFNSKeyValueObservingOptionsEnumData *> *)
options
error:(FlutterError *_Nullable *_Nonnull)error {
NSKeyValueObservingOptions optionsInt = 0;
for (FWFNSKeyValueObservingOptionsEnumData *data in options) {
optionsInt |= FWFNSKeyValueObservingOptionsFromEnumData(data);
}
[[self objectForIdentifier:identifier] addObserver:[self objectForIdentifier:observer]
forKeyPath:keyPath
options:optionsInt
context:nil];
}
- (void)removeObserverForObjectWithIdentifier:(nonnull NSNumber *)identifier
observerIdentifier:(nonnull NSNumber *)observer
keyPath:(nonnull NSString *)keyPath
error:(FlutterError *_Nullable *_Nonnull)error {
[[self objectForIdentifier:identifier] removeObserver:[self objectForIdentifier:observer]
forKeyPath:keyPath];
}
- (void)disposeObjectWithIdentifier:(nonnull NSNumber *)identifier
error:(FlutterError *_Nullable *_Nonnull)error {
[self.instanceManager removeInstanceWithIdentifier:identifier.longValue];
}
@end
| plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFObjectHostApi.m/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFObjectHostApi.m",
"repo_id": "plugins",
"token_count": 2371
} | 1,357 |
// Copyright 2013 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:math';
import 'package:flutter/foundation.dart';
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#106316)
// ignore: unnecessary_import
import 'package:flutter/painting.dart' show Color;
import 'package:flutter/services.dart';
import '../common/instance_manager.dart';
import '../foundation/foundation.dart';
import '../web_kit/web_kit.dart';
import 'ui_kit_api_impls.dart';
/// A view that allows the scrolling and zooming of its contained views.
///
/// Wraps [UIScrollView](https://developer.apple.com/documentation/uikit/uiscrollview?language=objc).
@immutable
class UIScrollView extends UIView {
/// Constructs a [UIScrollView] that is owned by [webView].
factory UIScrollView.fromWebView(
WKWebView webView, {
BinaryMessenger? binaryMessenger,
InstanceManager? instanceManager,
}) {
final UIScrollView scrollView = UIScrollView.detached(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
);
scrollView._scrollViewApi.createFromWebViewForInstances(
scrollView,
webView,
);
return scrollView;
}
/// Constructs a [UIScrollView] without creating the associated
/// Objective-C object.
///
/// This should only be used by subclasses created by this library or to
/// create copies.
UIScrollView.detached({
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _scrollViewApi = UIScrollViewHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached();
final UIScrollViewHostApiImpl _scrollViewApi;
/// Point at which the origin of the content view is offset from the origin of the scroll view.
///
/// Represents [WKWebView.contentOffset](https://developer.apple.com/documentation/uikit/uiscrollview/1619404-contentoffset?language=objc).
Future<Point<double>> getContentOffset() {
return _scrollViewApi.getContentOffsetForInstances(this);
}
/// Move the scrolled position of this view.
///
/// This method is not a part of UIKit and is only a helper method to make
/// scrollBy atomic.
Future<void> scrollBy(Point<double> offset) {
return _scrollViewApi.scrollByForInstances(this, offset);
}
/// Set point at which the origin of the content view is offset from the origin of the scroll view.
///
/// The default value is `Point<double>(0.0, 0.0)`.
///
/// Sets [WKWebView.contentOffset](https://developer.apple.com/documentation/uikit/uiscrollview/1619404-contentoffset?language=objc).
Future<void> setContentOffset(Point<double> offset) {
return _scrollViewApi.setContentOffsetForInstances(this, offset);
}
@override
UIScrollView copy() {
return UIScrollView.detached(
observeValue: observeValue,
binaryMessenger: _viewApi.binaryMessenger,
instanceManager: _viewApi.instanceManager,
);
}
}
/// Manages the content for a rectangular area on the screen.
///
/// Wraps [UIView](https://developer.apple.com/documentation/uikit/uiview?language=objc).
@immutable
class UIView extends NSObject {
/// Constructs a [UIView] without creating the associated
/// Objective-C object.
///
/// This should only be used by subclasses created by this library or to
/// create copies.
UIView.detached({
super.observeValue,
super.binaryMessenger,
super.instanceManager,
}) : _viewApi = UIViewHostApiImpl(
binaryMessenger: binaryMessenger,
instanceManager: instanceManager,
),
super.detached();
final UIViewHostApiImpl _viewApi;
/// The view’s background color.
///
/// The default value is null, which results in a transparent background color.
///
/// Sets [UIView.backgroundColor](https://developer.apple.com/documentation/uikit/uiview/1622591-backgroundcolor?language=objc).
Future<void> setBackgroundColor(Color? color) {
return _viewApi.setBackgroundColorForInstances(this, color);
}
/// Determines whether the view is opaque.
///
/// Sets [UIView.opaque](https://developer.apple.com/documentation/uikit/uiview?language=objc).
Future<void> setOpaque(bool opaque) {
return _viewApi.setOpaqueForInstances(this, opaque);
}
@override
UIView copy() {
return UIView.detached(
observeValue: observeValue,
binaryMessenger: _viewApi.binaryMessenger,
instanceManager: _viewApi.instanceManager,
);
}
}
| plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/ui_kit/ui_kit.dart/0 | {
"file_path": "plugins/packages/webview_flutter/webview_flutter_wkwebview/lib/src/ui_kit/ui_kit.dart",
"repo_id": "plugins",
"token_count": 1577
} | 1,358 |
This folder contains configuration files that are passed to commands in place
of plugin lists. They are primarily used by CI to opt specific packages out of
tests, but can also useful when running multi-plugin tests locally.
**Any entry added to a file in this directory should include a comment**.
Skipping tests or checks for plugins is usually not something we want to do,
so should the comment should either include an issue link to the issue tracking
removing it or—much more rarely—explaining why it is a permanent exclusion.
| plugins/script/configs/README.md/0 | {
"file_path": "plugins/script/configs/README.md",
"repo_id": "plugins",
"token_count": 115
} | 1,359 |
# Contributing
_See also: [Flutter's code of conduct](https://github.com/flutter/flutter/blob/master/CODE_OF_CONDUCT.md)_
Want to contribute to the Flutter sample ecosystem? Great! First, read this
page (including the small print at the end).
## Is this the right place for your contribution?
This repo is used by members of the Flutter team and a few partners as a place
to store example apps and demos. It's not meant to be the one and only source of
truth for Flutter samples or the only place people go to learn about the best
ways to build with Flutter. What that means in practice is that if you've
written a great example app, it doesn't need to be maintained here in order to
get noticed, be of help to new Flutter devs, and have an impact on the
community.
You can maintain your sample app in your own repo (or with another source
control provider) and still be as important a part of the Flutter-verse as
anything you see here. You can let us know on the
[FlutterDev Google Group](https://groups.google.com/forum/#!forum/flutter-dev)
when you've published something and Tweet about it with the
[#FlutterDev](https://twitter.com/search?q=%23FlutterDev) hashtag.
## So what should be contributed here, then?
Fixes and necessary improvements to the existing samples, mostly.
## Before you contribute
### File an issue first!
If you see a bug or have an idea for a feature that you feel would improve one
of the samples already in the repo, **please
[file an issue](https://github.com/flutter/samples/issues/new) before you begin
coding or send a PR**. This will help prevent duplicate work by letting us know
what you're up to. It will help avoid a situation in which you spend a lot of
time coding something that's not quite right for the repo or its goals.
### Sign the license agreement.
Before we can use your code, you must sign the
[Google Individual Contributor License Agreement](https://cla.developers.google.com/about/google-individual)
(CLA), which you can do online. The CLA is necessary mainly because you own the
copyright to your changes, even after your contribution becomes part of our
codebase, so we need your permission to use and distribute your code. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.
## A few ground rules
This is monorepo containing a bunch of projects. While different codebases have
different needs, there are a few basic conventions that every project here is
expected to follow. All of them are based on our experience over the last
couple years keeping the repo tidy and running smooth.
Each app should:
* Be designed to build against the current
[stable](https://github.com/flutter/flutter/wiki/Flutter-build-release-channels)
release of the Flutter SDK.
* Include the top level
[`analysis_options.yaml`](analysis_options.yaml)
file used throughout the repo. This file include a base set of analyzer
conventions and lints.
* Have no analyzer errors or warnings.
* Be formatted with `dart format`.
* Include at least one working test in its `test` folder.
* Be wired into the list of projects in the CI scripts for [stable](tool/flutter_ci_script_stable.sh),
[beta](tool/flutter_ci_script_beta.sh), and [master](tool/flutter_ci_script_master.sh),
which runs the analyzer, the formatter, and `flutter test`.
* Add the new project directory to the [dependabot](.github/dependabot.yaml) configuration
to keep dependencies updated in an on-going basis.
* Avoid adding an onerous amount of blobs (typically images or other assets) to
the repo.
In addition, sample code is, at the end of the day, still code. It should be
written with at least as much care as the Flutter code you'd find in the SDK
itself. For that reason, most of the
[Flutter style guide](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo)
also applies to code in this repo.
### The `experimental` folder
Projects in the repo's top-level `experimental` directory are allowed to skirt
some of the above rules. These apps are either experimental in nature or use
APIs that haven't landed in the SDK's `stable` channel. They build against
`main`, and aren't (by default) wired into our CI system.
## Code reviews
All submissions, including submissions by project members, require review.
This repo is part of the [Flutter](https://github.com/flutter) GitHub account,
which means that a lot of folks have the ability to push and merge code. The
primary maintainers, though, are:
* [@RedBrogdon](https://github.com/RedBrogdon)
* [@johnpryan](https://github.com/johnpryan)
* [@domesticmouse](https://github.com/domesticmouse)
* [@ericwindmill](https://github.com/ericwindmill)
You are free to add one of these folks (particularly @RedBrogdon) as a reviewer
to any PR sent to this repo. We're happy to comment, answer (or ask) questions,
and provide feedback.
If you're part of a team that's already landed a sample in the repo (Hi,
Material!), and you're updating or fixing that sample, you are *not* expected to
wait on one of the above folks before merging the code. Have it reviewed by
someone you trust on your own team, and then merge it.
However, if you're adding a new sample, updating a sample you've never worked on
before, or changing something that's a meta-concern like the CI setup, web
hosting, project setup, etc., please include one of the primary maintainers as a
reviewer.
## File headers
All files in the project must start with the following header.
```
// Copyright 2023 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.
```
## The small print
Contributions made by corporations are covered by a different agreement than the
one above, the
[Software Grant and Corporate Contributor License Agreement](https://developers.google.com/open-source/cla/corporate).
| samples/CONTRIBUTING.md/0 | {
"file_path": "samples/CONTRIBUTING.md",
"repo_id": "samples",
"token_count": 1674
} | 1,360 |
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M3,13h8L11,3L3,3v10zM3,21h8v-6L3,15v6zM13,21h8L21,11h-8v10zM13,3v6h8L21,3h-8z" />
</vector>
| samples/add_to_app/android_view/android_view/app/src/main/res/drawable/ic_dashboard_black_24dp.xml/0 | {
"file_path": "samples/add_to_app/android_view/android_view/app/src/main/res/drawable/ic_dashboard_black_24dp.xml",
"repo_id": "samples",
"token_count": 181
} | 1,361 |
include: package:analysis_defaults/flutter.yaml
| samples/add_to_app/android_view/flutter_module_using_plugin/analysis_options.yaml/0 | {
"file_path": "samples/add_to_app/android_view/flutter_module_using_plugin/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,362 |
// Copyright 2020 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.
package dev.flutter.example.books
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import com.google.android.material.button.MaterialButton
import com.google.gson.GsonBuilder
import com.google.gson.JsonParser
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.lang.Exception
import java.lang.RuntimeException
class MainActivity : AppCompatActivity() {
companion object {
const val BOOKS_QUERY = "https://www.googleapis.com/books/v1/volumes?q=greenwood+tulsa&maxResults=15"
}
private lateinit var books: MutableList<Api.Book>
private lateinit var list: LinearLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
list = findViewById<LinearLayout>(R.id.list)
// OkHttp is arbitrarily chosen here to represent an existing middleware constraint that's
// already present in an existing application's infrastructure.
val httpClient = OkHttpClient()
val bookRequest = Request.Builder()
// Retrieve data from Google Books API (arbitrarily chosen). This represents existing
// data sources that an existing application is already interfacing with.
.url(BOOKS_QUERY)
.build()
httpClient.newCall(bookRequest).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
throw e
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
books = parseGoogleBooksJsonToBooks(response.body!!.string())
val spinner = findViewById<ProgressBar>(R.id.spinner)
runOnUiThread {
// Showed a spinner while network call is in progress. Remove it when
// response is received.
spinner.visibility = View.GONE
populateBookCards()
}
}
}
})
}
// Take a top level Google Books query's response JSON and create a list of Book Pigeon data
// classes that will be used both as a model here on the Kotlin side and also in the IPCs
// to Dart.
private fun parseGoogleBooksJsonToBooks(jsonBody: String): MutableList<Api.Book> {
// Here we're arbitrarily using GSON to represent another existing middleware constraint
// that already exists in your existing application's infrastructure.
val jsonBooks = JsonParser.parseString(jsonBody).asJsonObject.getAsJsonArray("items")
val books = mutableListOf<Api.Book>()
for (jsonBook in jsonBooks.map { it.asJsonObject }) {
try {
// Here we're using GSON to populate a Pigeon data class directly. The Pigeon data
// class can be used not just as part of your IPC API's signature but also as a
// normal data class in your existing application.
//
// We could either push the Pigeon data class usage higher into the existing GSON
// "middleware" or lower, closer to the IPC.
val book = Api.Book()
val volumeInfoJson = jsonBook.getAsJsonObject("volumeInfo")
book.title = volumeInfoJson.get("title").asString
book.subtitle = volumeInfoJson.get("subtitle")?.asString
// Sorry co-authors, we're trying to keep this simple.
book.author = volumeInfoJson.getAsJsonArray("authors")[0].asString
book.summary = volumeInfoJson.get("description").asString
book.publishDate = volumeInfoJson.get("publishedDate").asString
book.pageCount = volumeInfoJson.get("pageCount").asLong
val thumbnail = Api.Thumbnail()
thumbnail.url = volumeInfoJson.getAsJsonObject("imageLinks").get("thumbnail").asString
book.thumbnail = thumbnail
books.add(book)
} catch (e: Exception) {
println("Failed to parse book:")
println(GsonBuilder().setPrettyPrinting().create().toJson(jsonBook))
println("Parsing error:")
println(e)
}
}
return books
}
// Given a populated books list, create a Material Design card in a scroll view for each book.
private fun populateBookCards() {
for ((index, book) in books.withIndex()) {
val card = layoutInflater.inflate(R.layout.book_card, null)
updateCardWithBook(card, book)
card.findViewById<MaterialButton>(R.id.edit).setOnClickListener {
// When the edit button is clicked in a book's card, launch a Flutter activity
// showing the details of the book.
startActivityForResult(
// We're using our own 'FlutterActivity' subclass which wraps Pigeon API usages
// into an idiomatic Android activity interface with intent extras as input and
// with activity 'setResult' as output.
//
// This lets activity-level feature developers abstract their Flutter usage
// and present a standard Android API to their upstream application developers.
//
// No Flutter-specific concepts are leaked outside the Flutter activity itself
// into the consuming class.
FlutterBookActivity
// Re-read from the 'books' list rather than just capturing the iterated
// 'book' instance since we change it when Dart updates it in onActivityResult.
.withBook(this, books[index]),
// The index lets us know which book we're returning the result for when we
// return from the Flutter activity.
index)
}
list.addView(card)
}
}
// Given a Material Design card and a book, update the card content to reflect the book model.
private fun updateCardWithBook(card: View, book: Api.Book) {
card.findViewById<TextView>(R.id.title).text = book.title
card.findViewById<TextView>(R.id.subtitle).text = book.subtitle
card.findViewById<TextView>(R.id.author).text = resources.getString(R.string.author_prefix, book.author)
}
// Callback when the Flutter activity started with 'startActivityForResult' above returns.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// The Flutter activity may cancel the edit. If so, don't update anything.
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
throw RuntimeException("The FlutterBookActivity returning RESULT_OK should always have a return data intent")
}
// If the book was edited in Flutter, the Flutter activity finishes and returns an
// activity result in an intent (the 'data' argument). The intent has an extra which is
// the edited book in serialized form.
val returnedBook = FlutterBookActivity.getBookFromResultIntent(data)
// Update our book model list.
books[requestCode] = returnedBook
// Refresh the UI here on the Kotlin side.
updateCardWithBook(list.getChildAt(requestCode), returnedBook)
}
}
}
| samples/add_to_app/books/android_books/app/src/main/java/dev/flutter/example/books/MainActivity.kt/0 | {
"file_path": "samples/add_to_app/books/android_books/app/src/main/java/dev/flutter/example/books/MainActivity.kt",
"repo_id": "samples",
"token_count": 3328
} | 1,363 |
// Copyright 2020 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 'package:pigeon/pigeon.dart';
class Book {
String? title;
String? subtitle;
String? author;
String? summary;
String? publishDate;
int? pageCount;
Thumbnail? thumbnail;
}
class Thumbnail {
String? url;
}
@FlutterApi()
abstract class FlutterBookApi {
void displayBookDetails(Book book);
}
@HostApi()
abstract class HostBookApi {
void cancel();
void finishEditingBook(Book book);
}
| samples/add_to_app/books/flutter_module_books/pigeon/schema.dart/0 | {
"file_path": "samples/add_to_app/books/flutter_module_books/pigeon/schema.dart",
"repo_id": "samples",
"token_count": 188
} | 1,364 |
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17506" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="b8i-Fj-lA1">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17505"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Navigation Controller-->
<scene sceneID="srE-pH-qZb">
<objects>
<navigationController id="b8i-Fj-lA1" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="wTo-xw-305">
<rect key="frame" x="0.0" y="44" width="414" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<color key="barTintColor" red="0.38431372549019605" green="0.0" blue="0.93333333333333335" alpha="0.84705882352941175" colorSpace="calibratedRGB"/>
<textAttributes key="titleTextAttributes">
<color key="textColor" systemColor="systemGray6Color"/>
</textAttributes>
</navigationBar>
<connections>
<segue destination="Xp0-05-6gn" kind="relationship" relationship="rootViewController" id="yik-Yg-HdC"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="NW2-DP-JZL" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-1328" y="-17"/>
</scene>
<!--Books-->
<scene sceneID="Ywb-fB-wBN">
<objects>
<tableViewController title="Books" id="Xp0-05-6gn" customClass="ViewController" customModule="IosBooks" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" allowsSelection="NO" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="uCy-ec-yGR">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="BookCell" rowHeight="190" id="SBb-uI-gbV" customClass="BookCell" customModule="IosBooks" customModuleProvider="target">
<rect key="frame" x="0.0" y="28" width="414" height="190"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="SBb-uI-gbV" id="C7V-w9-p66">
<rect key="frame" x="0.0" y="0.0" width="414" height="190"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Book Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="7KN-aJ-DT5">
<rect key="frame" x="20" y="11" width="374" height="29"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="24"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="2" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Uh5-nw-lRt">
<rect key="frame" x="20" y="48" width="374" height="41"/>
<string key="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc velit orci, varius tincidunt nisi ac, porta porta ipsum. Pellentesque feugiat consequat massa, facilisis euismod turpis aliquam at. Suspendisse mollis volutpat lacinia. Aenean tristique porttitor purus, eu porta sem tempor sit amet. </string>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="By: Foobar F. Foobar" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="76v-Ju-4Wc">
<rect key="frame" x="20" y="111" width="374" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="b0u-fM-VM6">
<rect key="frame" x="350" y="140" width="44" height="44"/>
<constraints>
<constraint firstAttribute="width" relation="greaterThanOrEqual" constant="44" id="Vf7-pJ-LZ3"/>
<constraint firstAttribute="height" constant="44" id="cfM-g4-ptv"/>
</constraints>
<state key="normal" title="Edit"/>
</button>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="b0u-fM-VM6" secondAttribute="bottom" constant="6" id="BPN-jO-sVu"/>
<constraint firstItem="7KN-aJ-DT5" firstAttribute="leading" secondItem="C7V-w9-p66" secondAttribute="leadingMargin" id="DsW-Gq-sjE"/>
<constraint firstItem="7KN-aJ-DT5" firstAttribute="trailing" secondItem="C7V-w9-p66" secondAttribute="trailingMargin" id="IVX-uA-An6"/>
<constraint firstItem="7KN-aJ-DT5" firstAttribute="top" secondItem="C7V-w9-p66" secondAttribute="topMargin" id="Iip-4a-2kS"/>
<constraint firstItem="76v-Ju-4Wc" firstAttribute="leading" secondItem="C7V-w9-p66" secondAttribute="leadingMargin" id="ZbD-YJ-kaV"/>
<constraint firstItem="76v-Ju-4Wc" firstAttribute="top" secondItem="Uh5-nw-lRt" secondAttribute="bottom" constant="22" id="cyp-xR-7If"/>
<constraint firstItem="b0u-fM-VM6" firstAttribute="trailing" secondItem="C7V-w9-p66" secondAttribute="trailingMargin" id="gSP-0I-VmO"/>
<constraint firstItem="b0u-fM-VM6" firstAttribute="leading" relation="greaterThanOrEqual" secondItem="C7V-w9-p66" secondAttribute="leadingMargin" id="gzq-Ig-PZI"/>
<constraint firstItem="b0u-fM-VM6" firstAttribute="top" secondItem="76v-Ju-4Wc" secondAttribute="bottom" constant="8" symbolic="YES" id="lCb-GM-BvA"/>
<constraint firstItem="Uh5-nw-lRt" firstAttribute="trailing" secondItem="C7V-w9-p66" secondAttribute="trailingMargin" id="p6I-sS-CN3"/>
<constraint firstItem="Uh5-nw-lRt" firstAttribute="leading" secondItem="C7V-w9-p66" secondAttribute="leadingMargin" id="qcT-uN-mqo"/>
<constraint firstItem="Uh5-nw-lRt" firstAttribute="top" secondItem="7KN-aJ-DT5" secondAttribute="bottom" constant="8" symbolic="YES" id="r2u-eT-RhX"/>
<constraint firstItem="76v-Ju-4Wc" firstAttribute="trailing" secondItem="C7V-w9-p66" secondAttribute="trailingMargin" id="zc4-dZ-JcM"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="byLine" destination="76v-Ju-4Wc" id="9Ky-Yc-aXU"/>
<outlet property="editButton" destination="b0u-fM-VM6" id="q99-MH-ThV"/>
<outlet property="subtitle" destination="Uh5-nw-lRt" id="UGS-IB-WV1"/>
<outlet property="title" destination="7KN-aJ-DT5" id="a5N-rW-azA"/>
</connections>
</tableViewCell>
</prototypes>
<sections/>
<connections>
<outlet property="dataSource" destination="Xp0-05-6gn" id="nso-Wx-y17"/>
<outlet property="delegate" destination="Xp0-05-6gn" id="Gk5-ND-hmv"/>
</connections>
</tableView>
<navigationItem key="navigationItem" id="Mr1-af-Ogz"/>
</tableViewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="17x-S3-agc" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-371.01449275362324" y="-17.410714285714285"/>
</scene>
</scenes>
<resources>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
<systemColor name="systemGray6Color">
<color red="0.94901960784313721" green="0.94901960784313721" blue="0.96862745098039216" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</systemColor>
</resources>
</document>
| samples/add_to_app/books/ios_books/IosBooks/Base.lproj/Main.storyboard/0 | {
"file_path": "samples/add_to_app/books/ios_books/IosBooks/Base.lproj/Main.storyboard",
"repo_id": "samples",
"token_count": 6080
} | 1,365 |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:exported="true"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:exported="true"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize" />
</application>
</manifest>
| samples/add_to_app/fullscreen/android_fullscreen/app/src/main/AndroidManifest.xml/0 | {
"file_path": "samples/add_to_app/fullscreen/android_fullscreen/app/src/main/AndroidManifest.xml",
"repo_id": "samples",
"token_count": 504
} | 1,366 |
include: package:analysis_defaults/flutter.yaml
| samples/add_to_app/fullscreen/flutter_module/analysis_options.yaml/0 | {
"file_path": "samples/add_to_app/fullscreen/flutter_module/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,367 |
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina6_1" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14490.49"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="IOSFullScreen" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Cnf-d3-wlx">
<rect key="frame" x="105" y="433" width="204" height="30"/>
<state key="normal" title="Launch Flutter ViewController"/>
<connections>
<action selector="buttonWasTapped:" destination="BYZ-38-t0r" eventType="primaryActionTriggered" id="yLP-26-wPf"/>
</connections>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Current counter: 0" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="KJB-T1-vx3">
<rect key="frame" x="136.5" y="380" width="141" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="Cnf-d3-wlx" firstAttribute="top" secondItem="KJB-T1-vx3" secondAttribute="bottom" constant="32" id="HZo-C0-7aM"/>
<constraint firstItem="Cnf-d3-wlx" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="IZY-8s-o5L"/>
<constraint firstItem="Cnf-d3-wlx" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="ofh-fr-CHR"/>
<constraint firstItem="KJB-T1-vx3" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="vxr-sw-WVe"/>
</constraints>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
<connections>
<outlet property="counterLabel" destination="KJB-T1-vx3" id="Uph-NZ-re8"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
| samples/add_to_app/fullscreen/ios_fullscreen/IOSFullScreen/Base.lproj/Main.storyboard/0 | {
"file_path": "samples/add_to_app/fullscreen/ios_fullscreen/IOSFullScreen/Base.lproj/Main.storyboard",
"repo_id": "samples",
"token_count": 2022
} | 1,368 |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Provide required visibility configuration for API level 30 and above -->
<queries>
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https" />
</intent>
</queries>
<application
android:name=".App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MultipleFlutters">
<activity
android:name=".MainActivity"
android:exported="true"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SingleFlutterActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
android:exported="true"
/>
<activity
android:name=".DoubleFlutterActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
android:exported="true"
/>
<!-- Whether leave or clean up the VM after the last shell shuts down. If your want to let
your app destroy the last shell and re-create shells more quickly, set it to true,
otherwise if you want to clean up the memory of the leak VM, set it to false.
(This setting works after the Flutter 2.10 stable version.)
View https://github.com/flutter/flutter/issues/95903 for more detail. -->
<meta-data
android:name="io.flutter.embedding.android.LeakVM"
android:value="false"
/>
</application>
</manifest> | samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/AndroidManifest.xml",
"repo_id": "samples",
"token_count": 1012
} | 1,369 |
include ':app'
rootProject.name = "Multiple Flutters"
setBinding(new Binding([gradle: this])) // new
evaluate(new File( // new
settingsDir.parentFile, // new
'./multiple_flutters_module/.android/include_flutter.groovy' // new
)) | samples/add_to_app/multiple_flutters/multiple_flutters_android/settings.gradle/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/settings.gradle",
"repo_id": "samples",
"token_count": 239
} | 1,370 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
</dict>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
| samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/Info.plist/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos/Info.plist",
"repo_id": "samples",
"token_count": 846
} | 1,371 |
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina6_1" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14490.49"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="IOSUsingPlugin" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="7AZ-pf-o8t">
<rect key="frame" x="105" y="433" width="204" height="30"/>
<state key="normal" title="Launch Flutter ViewController"/>
<connections>
<action selector="buttonWasTapped:" destination="BYZ-38-t0r" eventType="touchUpInside" id="CWl-ky-Fi7"/>
</connections>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Current counter: 0" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="CRH-Pl-iAx">
<rect key="frame" x="136.5" y="380" width="141" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="CRH-Pl-iAx" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="8uI-oh-Mct"/>
<constraint firstItem="7AZ-pf-o8t" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="ak8-KP-rJR"/>
<constraint firstItem="7AZ-pf-o8t" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="tz6-fF-pgl"/>
<constraint firstItem="7AZ-pf-o8t" firstAttribute="top" secondItem="CRH-Pl-iAx" secondAttribute="bottom" constant="32" id="xwu-mc-qrx"/>
</constraints>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
<connections>
<outlet property="counterLabel" destination="CRH-Pl-iAx" id="MDk-m4-JQj"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
| samples/add_to_app/plugin/ios_using_plugin/IOSUsingPlugin/Base.lproj/Main.storyboard/0 | {
"file_path": "samples/add_to_app/plugin/ios_using_plugin/IOSUsingPlugin/Base.lproj/Main.storyboard",
"repo_id": "samples",
"token_count": 2011
} | 1,372 |
include: package:analysis_defaults/flutter.yaml
| samples/add_to_app/prebuilt_module/flutter_module/analysis_options.yaml/0 | {
"file_path": "samples/add_to_app/prebuilt_module/flutter_module/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,373 |
// Copyright 2019 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 UIKit
import Flutter
class ViewController: UIViewController {
@IBOutlet weak var counterLabel: UILabel!
var methodChannel : FlutterMethodChannel?
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
if let flutterEngine = (UIApplication.shared.delegate as? AppDelegate)?.flutterEngine {
methodChannel = FlutterMethodChannel(name: "dev.flutter.example/counter",
binaryMessenger: flutterEngine.binaryMessenger)
methodChannel?.setMethodCallHandler({ [weak self]
(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
if let strongSelf = self {
switch(call.method) {
case "incrementCounter":
strongSelf.count += 1
strongSelf.counterLabel.text = "Current counter: \(strongSelf.count)"
strongSelf.reportCounter()
case "requestCounter":
strongSelf.reportCounter()
default:
// Unrecognized method name
print("Unrecognized method name: \(call.method)")
}
}
})
}
}
func reportCounter() {
methodChannel?.invokeMethod("reportCounter", arguments: count)
}
@IBAction func buttonWasTapped(_ sender: Any) {
if let flutterEngine = (UIApplication.shared.delegate as? AppDelegate)?.flutterEngine {
let flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
self.present(flutterViewController, animated: false, completion: nil)
}
}
}
| samples/add_to_app/prebuilt_module/ios_using_prebuilt_module/IOSUsingPrebuiltModule/ViewController.swift/0 | {
"file_path": "samples/add_to_app/prebuilt_module/ios_using_prebuilt_module/IOSUsingPrebuiltModule/ViewController.swift",
"repo_id": "samples",
"token_count": 879
} | 1,374 |
<!--
~ Copyright (C) 2021 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!-- This is the animated Android icon that initiates the entire splash screen animation-->
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt">
<aapt:attr name="android:drawable">
<vector
android:width="108dp"
android:height="108dp"
android:viewportHeight="432"
android:viewportWidth="432">
<!--
Scale down the icon and translate if to fit
within the inner 2/3 (scale <= 0.67) or the viewport.
-->
<group
android:translateX="97"
android:translateY="97"
android:scaleX="0.55"
android:scaleY="0.55">
<clip-path android:pathData="m322.02,167.89c12.141,-21.437 25.117,-42.497 36.765,-64.158 2.2993,-7.7566 -9.5332,-12.802 -13.555,-5.7796 -12.206,21.045 -24.375,42.112 -36.567,63.166 -57.901,-26.337 -127.00,-26.337 -184.90,0.0 -12.685,-21.446 -24.606,-43.441 -37.743,-64.562 -5.6074,-5.8390 -15.861,1.9202 -11.747,8.8889 12.030,20.823 24.092,41.629 36.134,62.446C47.866,200.90 5.0987,267.15 0.0,337.5c144.00,0.0 288.00,0.0 432.0,0.0C426.74,267.06 384.46,201.32 322.02,167.89ZM116.66,276.03c-13.076,0.58968 -22.531,-15.277 -15.773,-26.469 5.7191,-11.755 24.196,-12.482 30.824,-1.2128 7.8705,11.451 -1.1102,28.027 -15.051,27.682zM315.55,276.03c-13.076,0.58968 -22.531,-15.277 -15.773,-26.469 5.7191,-11.755 24.196,-12.482 30.824,-1.2128 7.8705,11.451 -1.1097,28.027 -15.051,27.682z" />
<path
android:fillColor="#3ddc84"
android:pathData="m322.02,167.89c12.141,-21.437 25.117,-42.497 36.765,-64.158 2.2993,-7.7566 -9.5332,-12.802 -13.555,-5.7796 -12.206,21.045 -24.375,42.112 -36.567,63.166 -57.901,-26.337 -127.00,-26.337 -184.90,0.0 -12.685,-21.446 -24.606,-43.441 -37.743,-64.562 -5.6074,-5.8390 -15.861,1.9202 -11.747,8.8889 12.030,20.823 24.092,41.629 36.134,62.446C47.866,200.90 5.0987,267.15 0.0,337.5c144.00,0.0 288.00,0.0 432.0,0.0C426.74,267.06 384.46,201.32 322.02,167.89ZM116.66,276.03c-13.076,0.58968 -22.531,-15.277 -15.773,-26.469 5.7191,-11.755 24.196,-12.482 30.824,-1.2128 7.8705,11.451 -1.1102,28.027 -15.051,27.682zM315.55,276.03c-13.076,0.58968 -22.531,-15.277 -15.773,-26.469 5.7191,-11.755 24.196,-12.482 30.824,-1.2128 7.8705,11.451 -1.1097,28.027 -15.051,27.682z"
android:strokeWidth="1.93078" />
<group android:name="anim">
<path
android:fillAlpha="0.999"
android:fillColor="#979797"
android:fillType="nonZero"
android:pathData="m-197.42,638.59c0.0,0.0 -5.9627,-259.30 46.113,-215.87 32.895,27.437 76.838,-65.597 91.553,-46.592 2.7119,-7.7182 95.045,109.16 139.74,17.953 10.678,-21.792 43.788,-64.489 78.236,-16.164 54.226,76.069 110.90,-100.75 179.84,-17.966 36.393,43.701 96.377,-23.605 148.05,19.889 42.614,35.869 83.166,3.7255 109.76,61.101 24.321,52.465 35.893,197.64 35.893,197.64L631.77,92.867L-197.42,92.867Z"
android:strokeAlpha="1"
android:strokeColor="#00000000"
android:strokeWidth="12" />
</group>
</group>
</vector>
</aapt:attr>
<target android:name="anim">
<aapt:attr name="android:animation">
<objectAnimator
android:duration="1000"
android:propertyName="translateY"
android:repeatCount="0"
android:valueFrom="0"
android:valueTo="-432"
android:valueType="floatType"
android:interpolator="@android:interpolator/accelerate_decelerate" />
</aapt:attr>
</target>
<target android:name="anim">
<aapt:attr name="android:animation">
<objectAnimator
android:duration="500"
android:propertyName="translateX"
android:repeatCount="-1"
android:repeatMode="reverse"
android:valueFrom="-162"
android:valueTo="162"
android:valueType="floatType"
android:interpolator="@android:interpolator/accelerate_decelerate" />
</aapt:attr>
</target>
</animated-vector> | samples/android_splash_screen/android/app/src/main/res/drawable/splashscreen_icon.xml/0 | {
"file_path": "samples/android_splash_screen/android/app/src/main/res/drawable/splashscreen_icon.xml",
"repo_id": "samples",
"token_count": 2232
} | 1,375 |
// Copyright 2019 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 'package:flutter/material.dart';
// Refer to the AnimatedWidget docs here - https://api.flutter.dev/flutter/widgets/AnimatedWidget-class.html
// for examples of other common animated widgets.
class FadeTransitionDemo extends StatefulWidget {
const FadeTransitionDemo({super.key});
static const String routeName = 'basics/fade_transition';
@override
State<FadeTransitionDemo> createState() => _FadeTransitionDemoState();
}
class _FadeTransitionDemoState extends State<FadeTransitionDemo>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _animation;
late final CurvedAnimation _curve;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 500),
);
_curve = CurvedAnimation(parent: _controller, curve: Curves.easeIn);
_animation = Tween(
begin: 1.0,
end: 0.0,
).animate(_curve);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
'Fade Transition',
),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FadeTransition(
opacity: _animation,
child: const Icon(
Icons.star,
color: Colors.amber,
size: 300,
),
),
ElevatedButton(
child: const Text('animate'),
onPressed: () => setState(() {
_controller.animateTo(1.0).then<TickerFuture>(
(value) => _controller.animateBack(0.0));
}),
),
],
),
),
);
}
}
| samples/animations/lib/src/basics/fade_transition.dart/0 | {
"file_path": "samples/animations/lib/src/basics/fade_transition.dart",
"repo_id": "samples",
"token_count": 890
} | 1,376 |
// Copyright 2019 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 'package:flutter/material.dart';
class RepeatingAnimationDemo extends StatefulWidget {
const RepeatingAnimationDemo({super.key});
static String routeName = 'misc/repeating_animation';
@override
State<RepeatingAnimationDemo> createState() => _RepeatingAnimationDemoState();
}
class _RepeatingAnimationDemoState extends State<RepeatingAnimationDemo>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<BorderRadius?> _borderRadius;
@override
void initState() {
super.initState();
_controller =
AnimationController(duration: const Duration(seconds: 2), vsync: this)
..repeat(reverse: true);
_borderRadius = BorderRadiusTween(
begin: BorderRadius.circular(100.0),
end: BorderRadius.circular(0.0),
).animate(_controller);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Repeating Animation')),
body: Center(
child: AnimatedBuilder(
animation: _borderRadius,
builder: (context, child) {
return Container(
width: 200,
height: 200,
decoration: BoxDecoration(
color: Colors.deepPurple,
borderRadius: _borderRadius.value,
),
);
},
),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
| samples/animations/lib/src/misc/repeating_animation.dart/0 | {
"file_path": "samples/animations/lib/src/misc/repeating_animation.dart",
"repo_id": "samples",
"token_count": 643
} | 1,377 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/animations/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/animations/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,378 |
# Code Sharing
A full-stack Dart application using Flutter on the client and
[`shelf`](https://pub.dev/packages/shelf) on the server. The Flutter app
itself is still the counter app, but the actual number is stored on the server
and incremented over HTTP using transport data classes understood by both the
Flutter client and shelf server.
## Goals
The goal of this sample is to demonstrate the mechanics of sharing business
logic between a Flutter client and a Dart server. The sample also includes a
slightly modified Dockerfile which is required to build a Docker image from
a Dart app containing nested packages.
## Project Structure
The sample's project structure is as follows:
```
code_sharing/
# Flutter app
client/
lib/
...
pubspec.yaml
...
# Shelf
server/
bin/
server.dart
pubspec.yaml
Dockerfile
# Common business logic
shared/
pubspec.yaml
lib/
...
```
## Recreating this on your own
Recreating this introductory project for yourself can be done in several steps.
1. Create a parent directory, likely sharing a name with your project or
product, which will contain everything.
2. Within that directory, run `flutter create client`. You may also name this
Flutter project `app`, `mobile`, `<project-name>-app` or anything else that
seems appropriate. At this point, your folder structure should look like this:
```
my_project/
client/
lib/
main.dart
pubspec.yaml
...
```
3. From the same location where you ran `flutter create`, run
`dart create -t server-shelf server`. You may also name this Shelf project,
`backend`, `api`, `<project-name>-server`, or anything else that seems
appropriate. At this point, your folder structure should look like this:
```
my_project/
client/
lib/
main.dart
pubspec.yaml
...
server/
bin/
server.dart
Dockerfile
pubspec.yaml
...
```
4. Enter your server directory (`cd server`), and run `dart create -t package shared`.
You may also name this package `common`, `domain`, `<project-name>-shared`, or
anything else that seems appropriate. At this point, your folder structure should
resemble the sample:
```
my_project/
client/
lib/
main.dart
pubspec.yaml
...
server/
bin/
server.dart
shared/
lib/
src/
...
shared.dart
pubspec.yaml
...
Dockerfile
pubspec.yaml
...
```
5. Next, begin granting access to your shared code by making the following
edits to your Flutter app's `pubspec.yaml` file. Open that file
(`client/pubspec.yaml`) and add the following dependency under the
`dependencies` block:
```
dependencies:
# Add these two lines:
shared:
path: ../server/shared
```
6. Next, finish granting access to your shared code by making the following
edits to your server's `pubspec.yaml` file. Open that file
(`server/pubspec.yaml`) and add the following dependency under the
`dependencies` block:
```
dependencies:
# Add these two lines:
shared:
path: ./shared
```
7. The final step is to adjust your `Dockerfile`, as it can no longer
successfully run `dart pub get` after only copying over the `pubspec.yaml`
file (that command now requires the entirety of your `shared` directory to be
present.
- Find the line that says `COPY pubspec.* ./`, and change it to `COPY . .`.
With that, you're ready to build and run the app.
## Running the sample
To run the sample, or an equivalent you've reconstructed yourself, choose a
runtime method below based on your needs.
### From the CLI
In one terminal window, run the following commands:
```sh
cd my_project/server
dart run bin/server.dart
```
In a separate terminal window, run the following commands:
```sh
cd my_project/client
flutter run
```
> Note: If you named your mobile client and backend servers something other
than `client` and `server`, you will need to substitute in those values above.
### Build and run with Docker
To build your server's Docker image, run the following commands in a terminal
window:
```sh
cd my_project/server
docker build . -t my_project_server
```
To run that image as a Docker container, run the following commands in a
terminal window:
```sh
docker run -it my_project_server
```
### Build and run with `docker-compose`
If you have [`docker-compose`](https://docs.docker.com/compose/install/)
installed on your machine, you can run the following command to build and
launch your server:
```sh
cd my_project
docker-compose up -d
```
And then later stop the server with:
```sh
docker-compose stop
``` | samples/code_sharing/README.md/0 | {
"file_path": "samples/code_sharing/README.md",
"repo_id": "samples",
"token_count": 1531
} | 1,379 |
version: "3.7"
services:
server:
build:
context: .
ports:
- 8080:8080
environment:
SERVER_PORT: "8080"
SERVER_URL: "localhost"
SERVER_SCHEME: "http"
| samples/code_sharing/docker-compose.yml/0 | {
"file_path": "samples/code_sharing/docker-compose.yml",
"repo_id": "samples",
"token_count": 100
} | 1,380 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'models.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$IncrementImpl _$$IncrementImplFromJson(Map<String, dynamic> json) =>
_$IncrementImpl(
by: json['by'] as int,
);
Map<String, dynamic> _$$IncrementImplToJson(_$IncrementImpl instance) =>
<String, dynamic>{
'by': instance.by,
};
_$CountImpl _$$CountImplFromJson(Map<String, dynamic> json) => _$CountImpl(
json['value'] as int,
);
Map<String, dynamic> _$$CountImplToJson(_$CountImpl instance) =>
<String, dynamic>{
'value': instance.value,
};
| samples/code_sharing/shared/lib/src/models.g.dart/0 | {
"file_path": "samples/code_sharing/shared/lib/src/models.g.dart",
"repo_id": "samples",
"token_count": 249
} | 1,381 |
#import "GeneratedPluginRegistrant.h"
| samples/context_menus/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/context_menus/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,382 |
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'constants.dart';
import 'platform_selector.dart';
class ModifiedActionPage extends StatelessWidget {
ModifiedActionPage({
super.key,
required this.onChangedPlatform,
});
static const String route = 'modified-action';
static const String title = 'Modified Action';
static const String subtitle =
'The copy button copies but also shows a menu.';
static const String url = '$kCodeUrl/modified_action_page.dart';
final PlatformCallback onChangedPlatform;
final TextEditingController _controller = TextEditingController(
text: 'Try using the copy button.',
);
DialogRoute _showDialog(BuildContext context) {
return DialogRoute<void>(
context: context,
builder: (context) => const AlertDialog(
title: Text('Copied, but also showed this dialog.')),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(ModifiedActionPage.title),
actions: <Widget>[
PlatformSelector(
onChangedPlatform: onChangedPlatform,
),
IconButton(
icon: const Icon(Icons.code),
onPressed: () async {
if (!await launchUrl(Uri.parse(url))) {
throw 'Could not launch $url';
}
},
),
],
),
body: Center(
child: SizedBox(
width: 300.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'This example shows adding to the behavior of a default button.',
),
const SizedBox(
height: 30.0,
),
TextField(
controller: _controller,
contextMenuBuilder: (context, editableTextState) {
final List<ContextMenuButtonItem> buttonItems =
editableTextState.contextMenuButtonItems;
// Modify the copy buttonItem to show a dialog after copying.
final int copyButtonIndex = buttonItems.indexWhere(
(buttonItem) {
return buttonItem.type == ContextMenuButtonType.copy;
},
);
if (copyButtonIndex >= 0) {
final ContextMenuButtonItem copyButtonItem =
buttonItems[copyButtonIndex];
buttonItems[copyButtonIndex] = copyButtonItem.copyWith(
onPressed: () {
copyButtonItem.onPressed!();
Navigator.of(context).push(_showDialog(context));
},
);
}
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: editableTextState.contextMenuAnchors,
buttonItems: buttonItems,
);
},
),
],
),
),
),
);
}
}
| samples/context_menus/lib/modified_action_page.dart/0 | {
"file_path": "samples/context_menus/lib/modified_action_page.dart",
"repo_id": "samples",
"token_count": 1542
} | 1,383 |
import 'package:context_menus/custom_buttons_page.dart';
import 'package:context_menus/main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Shows custom buttons in the built-in context menu',
(tester) async {
await tester.pumpWidget(const MyApp());
// Navigate to the CustomButtonsPage example.
await tester.dragUntilVisible(
find.text(CustomButtonsPage.title),
find.byType(ListView),
const Offset(0.0, -100.0),
);
await tester.pumpAndSettle();
await tester.tap(find.text(CustomButtonsPage.title));
await tester.pumpAndSettle();
// Right click on the text field to show the context menu.
final TestGesture gesture = await tester.startGesture(
tester.getCenter(find.byType(EditableText)),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// The context menu is shown, and the buttons are custom widgets.
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
expect(find.byType(CupertinoTextSelectionToolbarButton), findsNothing);
expect(find.byType(CupertinoButton), findsNWidgets(2));
case TargetPlatform.macOS:
expect(find.byType(CupertinoButton), findsNWidgets(2));
expect(find.byType(CupertinoDesktopTextSelectionToolbarButton),
findsNothing);
case TargetPlatform.android:
case TargetPlatform.fuchsia:
expect(find.byType(CupertinoButton), findsNWidgets(1));
expect(find.byType(TextSelectionToolbarTextButton), findsNothing);
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(find.byType(CupertinoButton), findsNWidgets(1));
expect(find.byType(DesktopTextSelectionToolbarButton), findsNothing);
}
});
}
| samples/context_menus/test/custom_buttons_page_test.dart/0 | {
"file_path": "samples/context_menus/test/custom_buttons_page_test.dart",
"repo_id": "samples",
"token_count": 797
} | 1,384 |
// Copyright 2019 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.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'search.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<Search> _$searchSerializer = new _$SearchSerializer();
class _$SearchSerializer implements StructuredSerializer<Search> {
@override
final Iterable<Type> types = const [Search, _$Search];
@override
final String wireName = 'Search';
@override
Iterable<Object?> serialize(Serializers serializers, Search object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[
'query',
serializers.serialize(object.query,
specifiedType: const FullType(String)),
'results',
serializers.serialize(object.results,
specifiedType:
const FullType(BuiltList, const [const FullType(Photo)])),
];
return result;
}
@override
Search deserialize(Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new SearchBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current! as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'query':
result.query = serializers.deserialize(value,
specifiedType: const FullType(String))! as String;
break;
case 'results':
result.results.replace(serializers.deserialize(value,
specifiedType:
const FullType(BuiltList, const [const FullType(Photo)]))!
as BuiltList<Object?>);
break;
}
}
return result.build();
}
}
class _$Search extends Search {
@override
final String query;
@override
final BuiltList<Photo> results;
factory _$Search([void Function(SearchBuilder)? updates]) =>
(new SearchBuilder()..update(updates))._build();
_$Search._({required this.query, required this.results}) : super._() {
BuiltValueNullFieldError.checkNotNull(query, r'Search', 'query');
BuiltValueNullFieldError.checkNotNull(results, r'Search', 'results');
}
@override
Search rebuild(void Function(SearchBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
SearchBuilder toBuilder() => new SearchBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Search && query == other.query && results == other.results;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, query.hashCode);
_$hash = $jc(_$hash, results.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'Search')
..add('query', query)
..add('results', results))
.toString();
}
}
class SearchBuilder implements Builder<Search, SearchBuilder> {
_$Search? _$v;
String? _query;
String? get query => _$this._query;
set query(String? query) => _$this._query = query;
ListBuilder<Photo>? _results;
ListBuilder<Photo> get results =>
_$this._results ??= new ListBuilder<Photo>();
set results(ListBuilder<Photo>? results) => _$this._results = results;
SearchBuilder();
SearchBuilder get _$this {
final $v = _$v;
if ($v != null) {
_query = $v.query;
_results = $v.results.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(Search other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$Search;
}
@override
void update(void Function(SearchBuilder)? updates) {
if (updates != null) updates(this);
}
@override
Search build() => _build();
_$Search _build() {
_$Search _$result;
try {
_$result = _$v ??
new _$Search._(
query: BuiltValueNullFieldError.checkNotNull(
query, r'Search', 'query'),
results: results.build());
} catch (_) {
late String _$failedField;
try {
_$failedField = 'results';
results.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
r'Search', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/fluent_ui/lib/src/model/search.g.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/model/search.g.dart",
"repo_id": "samples",
"token_count": 1760
} | 1,385 |
// Copyright 2019 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.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'position.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<Position> _$positionSerializer = new _$PositionSerializer();
class _$PositionSerializer implements StructuredSerializer<Position> {
@override
final Iterable<Type> types = const [Position, _$Position];
@override
final String wireName = 'Position';
@override
Iterable<Object?> serialize(Serializers serializers, Position object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[
'latitude',
serializers.serialize(object.latitude,
specifiedType: const FullType(double)),
'longitude',
serializers.serialize(object.longitude,
specifiedType: const FullType(double)),
];
return result;
}
@override
Position deserialize(Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new PositionBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current! as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'latitude':
result.latitude = serializers.deserialize(value,
specifiedType: const FullType(double))! as double;
break;
case 'longitude':
result.longitude = serializers.deserialize(value,
specifiedType: const FullType(double))! as double;
break;
}
}
return result.build();
}
}
class _$Position extends Position {
@override
final double latitude;
@override
final double longitude;
factory _$Position([void Function(PositionBuilder)? updates]) =>
(new PositionBuilder()..update(updates))._build();
_$Position._({required this.latitude, required this.longitude}) : super._() {
BuiltValueNullFieldError.checkNotNull(latitude, r'Position', 'latitude');
BuiltValueNullFieldError.checkNotNull(longitude, r'Position', 'longitude');
}
@override
Position rebuild(void Function(PositionBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
PositionBuilder toBuilder() => new PositionBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Position &&
latitude == other.latitude &&
longitude == other.longitude;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, latitude.hashCode);
_$hash = $jc(_$hash, longitude.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'Position')
..add('latitude', latitude)
..add('longitude', longitude))
.toString();
}
}
class PositionBuilder implements Builder<Position, PositionBuilder> {
_$Position? _$v;
double? _latitude;
double? get latitude => _$this._latitude;
set latitude(double? latitude) => _$this._latitude = latitude;
double? _longitude;
double? get longitude => _$this._longitude;
set longitude(double? longitude) => _$this._longitude = longitude;
PositionBuilder();
PositionBuilder get _$this {
final $v = _$v;
if ($v != null) {
_latitude = $v.latitude;
_longitude = $v.longitude;
_$v = null;
}
return this;
}
@override
void replace(Position other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$Position;
}
@override
void update(void Function(PositionBuilder)? updates) {
if (updates != null) updates(this);
}
@override
Position build() => _build();
_$Position _build() {
final _$result = _$v ??
new _$Position._(
latitude: BuiltValueNullFieldError.checkNotNull(
latitude, r'Position', 'latitude'),
longitude: BuiltValueNullFieldError.checkNotNull(
longitude, r'Position', 'longitude'));
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/position.g.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/position.g.dart",
"repo_id": "samples",
"token_count": 1574
} | 1,386 |
// Copyright 2019 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.
// TODO: Retrieve an API Access Key from https://unsplash.com/developers
const String unsplashAccessKey = '';
// The application name for the above API Access Key.
const unsplashAppName = '';
| samples/desktop_photo_search/fluent_ui/lib/unsplash_access_key.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/unsplash_access_key.dart",
"repo_id": "samples",
"token_count": 98
} | 1,387 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/desktop_photo_search/fluent_ui/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,388 |
include: package:analysis_defaults/flutter.yaml
linter:
rules:
sort_pub_dependencies: true
| samples/desktop_photo_search/material/analysis_options.yaml/0 | {
"file_path": "samples/desktop_photo_search/material/analysis_options.yaml",
"repo_id": "samples",
"token_count": 36
} | 1,389 |
// Copyright 2019 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.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'location.dart';
// **************************************************************************
// BuiltValueGenerator
// **************************************************************************
Serializer<Location> _$locationSerializer = new _$LocationSerializer();
class _$LocationSerializer implements StructuredSerializer<Location> {
@override
final Iterable<Type> types = const [Location, _$Location];
@override
final String wireName = 'Location';
@override
Iterable<Object?> serialize(Serializers serializers, Location object,
{FullType specifiedType = FullType.unspecified}) {
final result = <Object?>[];
Object? value;
value = object.city;
if (value != null) {
result
..add('city')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.country;
if (value != null) {
result
..add('country')
..add(serializers.serialize(value,
specifiedType: const FullType(String)));
}
value = object.position;
if (value != null) {
result
..add('position')
..add(serializers.serialize(value,
specifiedType: const FullType(Position)));
}
return result;
}
@override
Location deserialize(Serializers serializers, Iterable<Object?> serialized,
{FullType specifiedType = FullType.unspecified}) {
final result = new LocationBuilder();
final iterator = serialized.iterator;
while (iterator.moveNext()) {
final key = iterator.current! as String;
iterator.moveNext();
final Object? value = iterator.current;
switch (key) {
case 'city':
result.city = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'country':
result.country = serializers.deserialize(value,
specifiedType: const FullType(String)) as String?;
break;
case 'position':
result.position.replace(serializers.deserialize(value,
specifiedType: const FullType(Position))! as Position);
break;
}
}
return result.build();
}
}
class _$Location extends Location {
@override
final String? city;
@override
final String? country;
@override
final Position? position;
factory _$Location([void Function(LocationBuilder)? updates]) =>
(new LocationBuilder()..update(updates))._build();
_$Location._({this.city, this.country, this.position}) : super._();
@override
Location rebuild(void Function(LocationBuilder) updates) =>
(toBuilder()..update(updates)).build();
@override
LocationBuilder toBuilder() => new LocationBuilder()..replace(this);
@override
bool operator ==(Object other) {
if (identical(other, this)) return true;
return other is Location &&
city == other.city &&
country == other.country &&
position == other.position;
}
@override
int get hashCode {
var _$hash = 0;
_$hash = $jc(_$hash, city.hashCode);
_$hash = $jc(_$hash, country.hashCode);
_$hash = $jc(_$hash, position.hashCode);
_$hash = $jf(_$hash);
return _$hash;
}
@override
String toString() {
return (newBuiltValueToStringHelper(r'Location')
..add('city', city)
..add('country', country)
..add('position', position))
.toString();
}
}
class LocationBuilder implements Builder<Location, LocationBuilder> {
_$Location? _$v;
String? _city;
String? get city => _$this._city;
set city(String? city) => _$this._city = city;
String? _country;
String? get country => _$this._country;
set country(String? country) => _$this._country = country;
PositionBuilder? _position;
PositionBuilder get position => _$this._position ??= new PositionBuilder();
set position(PositionBuilder? position) => _$this._position = position;
LocationBuilder();
LocationBuilder get _$this {
final $v = _$v;
if ($v != null) {
_city = $v.city;
_country = $v.country;
_position = $v.position?.toBuilder();
_$v = null;
}
return this;
}
@override
void replace(Location other) {
ArgumentError.checkNotNull(other, 'other');
_$v = other as _$Location;
}
@override
void update(void Function(LocationBuilder)? updates) {
if (updates != null) updates(this);
}
@override
Location build() => _build();
_$Location _build() {
_$Location _$result;
try {
_$result = _$v ??
new _$Location._(
city: city, country: country, position: _position?.build());
} catch (_) {
late String _$failedField;
try {
_$failedField = 'position';
_position?.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
r'Location', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
// ignore_for_file: deprecated_member_use_from_same_package,type=lint
| samples/desktop_photo_search/material/lib/src/unsplash/location.g.dart/0 | {
"file_path": "samples/desktop_photo_search/material/lib/src/unsplash/location.g.dart",
"repo_id": "samples",
"token_count": 1953
} | 1,390 |
// Copyright 2019 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 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart' as url_launcher;
class PolicyDialog extends StatelessWidget {
const PolicyDialog({super.key});
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Terms & Conditions'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RichText(
textAlign: TextAlign.left,
text: TextSpan(
text: '• ',
style: const TextStyle(color: Colors.black, fontSize: 18),
children: [
TextSpan(
text: 'https://policies.google.com/terms',
style: const TextStyle(
fontWeight: FontWeight.bold, color: Colors.lightBlue),
recognizer: TapGestureRecognizer()
..onTap = () async {
final url =
Uri.parse('https://policies.google.com/terms');
if (await url_launcher.canLaunchUrl(url)) {
await url_launcher.launchUrl(url);
}
},
)
],
),
),
RichText(
textAlign: TextAlign.left,
text: TextSpan(
text: '• ',
style: const TextStyle(color: Colors.black, fontSize: 18),
children: [
TextSpan(
text: 'https://unsplash.com/terms',
style: const TextStyle(
fontWeight: FontWeight.bold, color: Colors.lightBlue),
recognizer: TapGestureRecognizer()
..onTap = () async {
final url = Uri.parse('https://unsplash.com/terms');
if (await url_launcher.canLaunchUrl(url)) {
await url_launcher.launchUrl(url);
}
},
)
],
),
),
],
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('CLOSE'),
),
],
);
}
}
| samples/desktop_photo_search/material/lib/src/widgets/policy_dialog.dart/0 | {
"file_path": "samples/desktop_photo_search/material/lib/src/widgets/policy_dialog.dart",
"repo_id": "samples",
"token_count": 1373
} | 1,391 |
# federated_plugin_example
Demonstrates how to use the federated_plugin plugin.
| samples/experimental/federated_plugin/federated_plugin/example/README.md/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/example/README.md",
"repo_id": "samples",
"token_count": 23
} | 1,392 |
include: package:analysis_defaults/flutter.yaml
| samples/experimental/federated_plugin/federated_plugin_macos/analysis_options.yaml/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_macos/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,393 |
include: package:analysis_defaults/flutter.yaml
| samples/experimental/federated_plugin/federated_plugin_web/analysis_options.yaml/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_web/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,394 |
// 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 'package:flutter/material.dart';
import 'package:linting_tool/layout/adaptive.dart';
import 'package:linting_tool/model/rules_store.dart';
import 'package:linting_tool/widgets/lint_expansion_tile.dart';
import 'package:provider/provider.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Consumer<RuleStore>(
builder: (context, rulesStore, child) {
if (rulesStore.isLoading) {
return const CircularProgressIndicator.adaptive();
}
if (rulesStore.rules.isNotEmpty) {
final isDesktop = isDisplayLarge(context);
final isTablet = isDisplayMedium(context);
final startPadding = isTablet
? 60.0
: isDesktop
? 120.0
: 16.0;
final endPadding = isTablet
? 60.0
: isDesktop
? 120.0
: 16.0;
return ListView.separated(
padding: EdgeInsetsDirectional.only(
start: startPadding,
end: endPadding,
top: isDesktop ? 28 : 16,
bottom: isDesktop ? kToolbarHeight : 16,
),
itemCount: rulesStore.rules.length,
cacheExtent: 5,
itemBuilder: (context, index) {
return LintExpansionTile(
rule: rulesStore.rules[index],
);
},
separatorBuilder: (context, index) => const SizedBox(height: 4),
);
}
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(rulesStore.error ?? 'Failed to load rules.'),
const SizedBox(
height: 16.0,
),
IconButton(
onPressed: () => rulesStore.fetchRules(),
icon: const Icon(Icons.refresh),
),
],
);
},
);
}
}
| samples/experimental/linting_tool/lib/pages/home_page.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/pages/home_page.dart",
"repo_id": "samples",
"token_count": 1070
} | 1,395 |
TODO: Add your license here.
| samples/experimental/pedometer/LICENSE/0 | {
"file_path": "samples/experimental/pedometer/LICENSE",
"repo_id": "samples",
"token_count": 10
} | 1,396 |
name: pedometer
description: A new Flutter FFI plugin project.
version: 0.0.1
publish_to: none
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.0.2
jni: ^0.7.2
ffi: ^2.1.0
dev_dependencies:
ffigen: ^11.0.0
jnigen: ^0.7.0
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# This section identifies this Flutter project as a plugin project.
# The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.)
# which should be registered in the plugin registry. This is required for
# using method channels.
# The Android 'package' specifies package in which the registered class is.
# This is required for using method channels on Android.
# The 'ffiPlugin' specifies that native code should be built and bundled.
# This is required for using `dart:ffi`.
# All these are used by the tooling to maintain consistency when
# adding or updating assets for this project.
#
# Please refer to README.md for a detailed explanation.
plugin:
platforms:
ios:
ffiPlugin: true
android:
ffiPlugin: true
# To add assets to your plugin package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.dev/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# To add custom fonts to your plugin package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.dev/custom-fonts/#from-packages
| samples/experimental/pedometer/pubspec.yaml/0 | {
"file_path": "samples/experimental/pedometer/pubspec.yaml",
"repo_id": "samples",
"token_count": 846
} | 1,397 |
# Type Jam
A simple typographically-themed puzzle app to explore creative use of variable fonts and shaders in Flutter.
| samples/experimental/varfont_shader_puzzle/README.md/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/README.md",
"repo_id": "samples",
"token_count": 28
} | 1,398 |
// Copyright 2023 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 'package:flutter/material.dart';
import '../components/components.dart';
import '../page_content/pages_flow.dart';
import '../styles.dart';
class PageNarrativePost extends NarrativePage {
const PageNarrativePost({
super.key,
required super.pageConfig,
});
@override
State<NarrativePage> createState() => _PageNarrativePostState();
}
class _PageNarrativePostState extends NarrativePageState {
@override
void initState() {
panels = [
LightboxedPanel(
pageConfig: widget.pageConfig,
fadeOnDismiss: false,
buildButton: true,
onDismiss: super.handleIntroDismiss,
content: [
Text(
'Whew, we put everything back together just before the font launch.',
style: TextStyles.bodyStyle(),
textAlign: TextAlign.left,
),
const SizedBox(
height: 8,
),
const Image(
image: AssetImage('assets/images/specimen-1.png'),
),
Text(
'As a reward, please enjoy the FontCo wallpapers on the next screen. Congratulations!',
style: TextStyles.bodyStyle(),
textAlign: TextAlign.left,
),
],
),
];
super.initState();
}
@override
Widget build(BuildContext context) {
return panels[panelIndex];
}
}
| samples/experimental/varfont_shader_puzzle/lib/page_content/page_narrative_post.dart/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/lib/page_content/page_narrative_post.dart",
"repo_id": "samples",
"token_count": 633
} | 1,399 |
// Copyright 2023 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.
#define PI 3.1415926538
uniform float uTime;
uniform vec2 uSize;
uniform float uDampener;
out vec4 fragColor;
uniform sampler2D uTexture;
void main()
{
float piTime = uTime * PI * 2;
vec2 texCoord = gl_FragCoord.xy / uSize.xy;
float offset = 50;
float opacSum = 0.0;
vec4 thisCol = texture(uTexture, texCoord.xy);
float x = texCoord.x + (offset / uSize.x * pow(sin(piTime), 4)) * uDampener;
if (x >= 0.0 && x <= 1.0) {
opacSum += 0.3 * texture(uTexture, vec2(x, texCoord.y)).a;
}
x = texCoord.x - (offset / uSize.x * pow(sin(piTime + PI), 2)) * uDampener;
if (x >= 0.0 && x <= 1.0) {
opacSum += 0.3 * texture(uTexture, vec2(x, texCoord.y)).a;
}
float y = texCoord.y + (offset / uSize.y * pow(sin(piTime + PI * 0.66), 4)) * uDampener;
if (y >= 0.0 && y <= 1.0) {
opacSum += 0.3 * texture(uTexture, vec2(texCoord.x, y)).a;
}
fragColor = vec4(0.0, 0.0, 0.0, clamp(opacSum, 0.0, 1.0));
}
| samples/experimental/varfont_shader_puzzle/shaders/bw_split.frag/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/shaders/bw_split.frag",
"repo_id": "samples",
"token_count": 482
} | 1,400 |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. 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:community_charts_flutter/community_charts_flutter.dart'
as charts;
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' as intl;
import '../api/api.dart';
import '../utils/chart_utils.dart' as utils;
import 'dialogs.dart';
// The number of days to show in the chart
const _daysBefore = 10;
class CategoryChart extends StatelessWidget {
final Category category;
final DashboardApi? api;
const CategoryChart({
required this.category,
required this.api,
super.key,
});
@override
Widget build(BuildContext context) {
return Column(
children: [
Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(category.name),
IconButton(
icon: const Icon(Icons.settings),
onPressed: () {
showDialog<EditCategoryDialog>(
context: context,
builder: (context) {
return EditCategoryDialog(category: category);
},
);
},
),
],
),
),
Expanded(
// Load the initial snapshot using a FutureBuilder, and subscribe to
// additional updates with a StreamBuilder.
child: FutureBuilder<List<Entry>>(
future: api!.entries.list(category.id!),
builder: (context, futureSnapshot) {
if (!futureSnapshot.hasData) {
return _buildLoadingIndicator();
}
return StreamBuilder<List<Entry>>(
initialData: futureSnapshot.data,
stream: api!.entries.subscribe(category.id!),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return _buildLoadingIndicator();
}
return _BarChart(entries: snapshot.data);
},
);
},
),
),
],
);
}
Widget _buildLoadingIndicator() {
return const Center(
child: CircularProgressIndicator(),
);
}
}
class _BarChart extends StatelessWidget {
final List<Entry>? entries;
const _BarChart({this.entries});
@override
Widget build(BuildContext context) {
return charts.BarChart(
[_seriesData()],
animate: false,
);
}
charts.Series<utils.EntryTotal, String> _seriesData() {
return charts.Series<utils.EntryTotal, String>(
id: 'Entries',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (entryTotal, _) {
var format = intl.DateFormat.Md();
return format.format(entryTotal.day);
},
measureFn: (total, _) {
return total.value;
},
data: utils.entryTotalsByDay(entries, _daysBefore),
);
}
}
| samples/experimental/web_dashboard/lib/src/widgets/category_chart.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/widgets/category_chart.dart",
"repo_id": "samples",
"token_count": 1464
} | 1,401 |
# Flutter Maps Firestore
A Flutter sample app that shows the end product of the Cloud Next '19 talk
[Build Mobile Apps With Flutter and Google Maps](https://www.youtube.com/watch?v=RpQLFAFqMlw).
The live coding starts at about 17:40.
## Goals for this sample
* Showcase how to build an app that uses Google Maps with Flutter:
* Loading a list of Ice Cream shops from Cloud Firestore
* Listing the shops in a custom carousel
* Showing the shop locations on a map using Markers
* Controlling the Google Map from the carousel
## The important bits
### Cloud Firestore
To set up Cloud Firestore connectivity, follow the steps outlined in the
[Cloud Firestore package setup section](https://pub.dev/packages/cloud_firestore#setup).
Next, you need to populate your Cloud Firestore with a collection named `ice_cream_stores`,
structured a bit like this:
```
ice_cream_stores:
ChIJ70taCKKAhYAR5IMmYwQT4Ts:
placeId: ChIJ70taCKKAhYAR5IMmYwQT4Ts
address: 432 Octavia St #1a, San Francisco, CA 94102, USA
location: 37.7763629, -122.4241918
name: Smitten Ice Cream
```
The collection name is referenced from `_HomePageState`'s `initState` method. The
`placeId`, `address`, `location` and `name` are used at various points in the widget
tree to render appropriate data.
### Google Maps
You need to add a Google Maps SDK for iOS API key to `ios/Runner/AppDelegate.m`.
This enables the Google Map to render. You will also need to add a Google Maps
Web Services API key to `lib/api_key.dart`.
To reiterate the warning that we gave during the talk, do not put Web Service API keys
in your production binary. You need to build a proxy service to serve
pre-authenticated content to your mobile applications so you can change API keys as
required. We only did this to make it easy to demonstrate on stage.
## Questions/issues
If you have a general question about building with Google Maps in Flutter, the
best places to go are:
* [The FlutterDev Google Group](https://groups.google.com/forum/#!forum/flutter-dev)
* [The Flutter Gitter channel](https://gitter.im/flutter/flutter)
* [StackOverflow](https://stackoverflow.com/questions/tagged/flutter)
If you run into an issue with the sample itself, please file an issue
in the [main Flutter repo](https://github.com/flutter/flutter/issues).
| samples/flutter_maps_firestore/README.md/0 | {
"file_path": "samples/flutter_maps_firestore/README.md",
"repo_id": "samples",
"token_count": 689
} | 1,402 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.game_template">
<application
android:label="game_template"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Google Mobile Ads -->
<!-- TODO: Replace the sample AdMob app ID with an actual app ID.
See README.txt for details. -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544~3347511713"/>
<!-- Google Play Games -->
<!-- Warning: Never include the Play Games app_id directly here.
It won't work. Use the XML file in res/values. -->
<meta-data
android:name="com.google.android.gms.games.APP_ID"
android:value="@string/app_id" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
| samples/game_template/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "samples/game_template/android/app/src/main/AndroidManifest.xml",
"repo_id": "samples",
"token_count": 1058
} | 1,403 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
const Set<Song> songs = {
// Filenames with whitespace break package:audioplayers on iOS
// (as of February 2022), so we use no whitespace.
Song('Mr_Smith-Azul.mp3', 'Azul', artist: 'Mr Smith'),
Song('Mr_Smith-Sonorus.mp3', 'Sonorus', artist: 'Mr Smith'),
Song('Mr_Smith-Sunday_Solitude.mp3', 'SundaySolitude', artist: 'Mr Smith'),
};
class Song {
final String filename;
final String name;
final String? artist;
const Song(this.filename, this.name, {this.artist});
@override
String toString() => 'Song<$filename>';
}
| samples/game_template/lib/src/audio/songs.dart/0 | {
"file_path": "samples/game_template/lib/src/audio/songs.dart",
"repo_id": "samples",
"token_count": 236
} | 1,404 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. 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:shared_preferences/shared_preferences.dart';
import 'settings_persistence.dart';
/// An implementation of [SettingsPersistence] that uses
/// `package:shared_preferences`.
class LocalStorageSettingsPersistence extends SettingsPersistence {
final Future<SharedPreferences> instanceFuture =
SharedPreferences.getInstance();
@override
Future<bool> getMusicOn() async {
final prefs = await instanceFuture;
return prefs.getBool('musicOn') ?? true;
}
@override
Future<bool> getMuted({required bool defaultValue}) async {
final prefs = await instanceFuture;
return prefs.getBool('mute') ?? defaultValue;
}
@override
Future<String> getPlayerName() async {
final prefs = await instanceFuture;
return prefs.getString('playerName') ?? 'Player';
}
@override
Future<bool> getSoundsOn() async {
final prefs = await instanceFuture;
return prefs.getBool('soundsOn') ?? true;
}
@override
Future<void> saveMusicOn(bool value) async {
final prefs = await instanceFuture;
await prefs.setBool('musicOn', value);
}
@override
Future<void> saveMuted(bool value) async {
final prefs = await instanceFuture;
await prefs.setBool('mute', value);
}
@override
Future<void> savePlayerName(String value) async {
final prefs = await instanceFuture;
await prefs.setString('playerName', value);
}
@override
Future<void> saveSoundsOn(bool value) async {
final prefs = await instanceFuture;
await prefs.setBool('soundsOn', value);
}
}
| samples/game_template/lib/src/settings/persistence/local_storage_settings_persistence.dart/0 | {
"file_path": "samples/game_template/lib/src/settings/persistence/local_storage_settings_persistence.dart",
"repo_id": "samples",
"token_count": 564
} | 1,405 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| samples/google_maps/android/gradle.properties/0 | {
"file_path": "samples/google_maps/android/gradle.properties",
"repo_id": "samples",
"token_count": 31
} | 1,406 |
package dev.flutter.infinite_list
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/infinite_list/android/app/src/main/kotlin/dev/flutter/infinite_list/MainActivity.kt/0 | {
"file_path": "samples/infinite_list/android/app/src/main/kotlin/dev/flutter/infinite_list/MainActivity.kt",
"repo_id": "samples",
"token_count": 40
} | 1,407 |
// Copyright 2019-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:isolate';
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class DataTransferPageStarter extends StatelessWidget {
const DataTransferPageStarter({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => DataTransferIsolateController(),
child: const DataTransferPage(),
);
}
}
class DataTransferPage extends StatelessWidget {
const DataTransferPage({super.key});
@override
Widget build(context) {
final controller = Provider.of<DataTransferIsolateController>(context);
return SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(8),
child: Text(
'Number Generator Progress',
style: Theme.of(context).textTheme.titleLarge,
),
),
LinearProgressIndicator(
value: controller.progressPercent,
backgroundColor: Colors.grey[200],
),
const Expanded(
child: RunningList(),
),
Column(
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
foregroundColor: switch (controller.runningTest) {
1 => Colors.blueAccent,
_ => Colors.blueGrey,
},
),
onPressed: () => controller.generateRandomNumbers(false),
child: const Text('Transfer Data to 2nd Isolate'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
foregroundColor: switch (controller.runningTest) {
2 => Colors.blueAccent,
_ => Colors.blueGrey,
},
),
onPressed: () => controller.generateRandomNumbers(true),
child: const Text('Transfer Data with TransferableTypedData'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
foregroundColor: switch (controller.runningTest) {
3 => Colors.blueAccent,
_ => Colors.blueGrey,
},
),
onPressed: controller.generateOnSecondaryIsolate,
child: const Text('Generate on 2nd Isolate'),
),
],
),
],
),
);
}
}
class DataTransferIsolateController extends ChangeNotifier {
Isolate? _isolate;
late ReceivePort _incomingReceivePort;
late SendPort _outgoingSendPort;
final currentProgress = <String>[];
int runningTest = 0;
Stopwatch _timer = Stopwatch();
double progressPercent = 0;
bool get running => runningTest != 0;
DataTransferIsolateController() {
createIsolate();
listen();
}
Future<void> createIsolate() async {
_incomingReceivePort = ReceivePort();
_isolate = await Isolate.spawn(
_secondIsolateEntryPoint, _incomingReceivePort.sendPort);
}
void listen() {
_incomingReceivePort.listen((dynamic message) {
switch (message) {
case SendPort():
_outgoingSendPort = message;
case int():
currentProgress.insert(
0, '$message% - ${_timer.elapsedMilliseconds / 1000} seconds');
progressPercent = message / 100;
case 'done':
runningTest = 0;
_timer.stop();
}
notifyListeners();
});
}
void generateOnSecondaryIsolate() {
if (running) return;
runningTest = 3;
currentProgress.clear();
_timer = Stopwatch();
_timer.start();
_outgoingSendPort.send('start');
notifyListeners();
}
Future<void> generateRandomNumbers(bool transferableTyped) async {
if (running) {
return;
}
if (transferableTyped) {
runningTest = 2;
} else {
runningTest = 1;
}
var random = Random();
currentProgress.clear();
_timer.reset();
_timer.start();
var randNums = <int>[];
for (var i = 0; i < 100; i++) {
randNums.clear();
for (var j = 0; j < 1000000; j++) {
randNums.add(random.nextInt(100));
}
if (transferableTyped) {
final transferable =
TransferableTypedData.fromList([Int32List.fromList(randNums)]);
await sendNumbers(transferable);
} else {
await sendNumbers(randNums);
}
}
}
Future<void> sendNumbers(dynamic numList) async {
return Future<void>(() {
_outgoingSendPort.send(numList);
});
}
@override
void dispose() {
super.dispose();
_isolate?.kill(priority: Isolate.immediate);
_isolate = null;
}
}
class RunningList extends StatelessWidget {
const RunningList({super.key});
@override
Widget build(BuildContext context) {
final progress =
Provider.of<DataTransferIsolateController>(context).currentProgress;
return DecoratedBox(
decoration: BoxDecoration(
color: Colors.grey[200],
),
child: ListView.builder(
itemCount: progress.length,
itemBuilder: (context, index) {
return Column(
children: [
Card(
color: Colors.lightGreenAccent,
child: ListTile(
title: Text(progress[index]),
),
),
const Divider(
color: Colors.blue,
height: 3,
),
],
);
},
),
);
}
}
Future<void> _secondIsolateEntryPoint(SendPort sendPort) async {
var receivePort = ReceivePort();
sendPort.send(receivePort.sendPort);
var length = 1;
receivePort.listen(
(dynamic message) async {
if (message is String && message == 'start') {
await generateAndSum(sendPort, createNums(), length);
sendPort.send('done');
} else if (message is TransferableTypedData) {
await generateAndSum(
sendPort, message.materialize().asInt32List(), length);
length++;
} else if (message is List<int>) {
await generateAndSum(sendPort, message, length);
length++;
}
if (length == 101) {
sendPort.send('done');
length = 1;
}
},
);
}
Iterable<int> createNums() sync* {
var random = Random();
for (var i = 0; i < 100000000; i++) {
yield random.nextInt(100);
}
}
Future<int> generateAndSum(
SendPort callerSP,
Iterable<int> iter,
int length,
) async {
var sum = 0;
var count = 1;
for (var x in iter) {
sum += x;
if (count % 1000000 == 0) {
callerSP.send((count ~/ 1000000) * length);
}
count++;
}
return sum;
}
| samples/isolate_example/lib/data_transfer_page.dart/0 | {
"file_path": "samples/isolate_example/lib/data_transfer_page.dart",
"repo_id": "samples",
"token_count": 3254
} | 1,408 |
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled.
version:
revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
channel: beta
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
base_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
- platform: android
create_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
base_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
- platform: ios
create_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
base_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
- platform: linux
create_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
base_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
- platform: macos
create_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
base_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
- platform: web
create_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
base_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
- platform: windows
create_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
base_revision: 0df8557c56a182d31fa024eeb08c428ae52edf7f
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
| samples/material_3_demo/.metadata/0 | {
"file_path": "samples/material_3_demo/.metadata",
"repo_id": "samples",
"token_count": 728
} | 1,409 |
// 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 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
const rowDivider = SizedBox(width: 20);
const colDivider = SizedBox(height: 10);
const tinySpacing = 3.0;
const smallSpacing = 10.0;
const double cardWidth = 115;
const double widthConstraint = 450;
class FirstComponentList extends StatelessWidget {
const FirstComponentList({
super.key,
required this.showNavBottomBar,
required this.scaffoldKey,
required this.showSecondList,
});
final bool showNavBottomBar;
final GlobalKey<ScaffoldState> scaffoldKey;
final bool showSecondList;
@override
Widget build(BuildContext context) {
List<Widget> children = [
const Actions(),
colDivider,
const Communication(),
colDivider,
const Containment(),
if (!showSecondList) ...[
colDivider,
Navigation(scaffoldKey: scaffoldKey),
colDivider,
const Selection(),
colDivider,
const TextInputs()
],
];
List<double?> heights = List.filled(children.length, null);
// Fully traverse this list before moving on.
return FocusTraversalGroup(
child: CustomScrollView(
slivers: [
SliverPadding(
padding: showSecondList
? const EdgeInsetsDirectional.only(end: smallSpacing)
: EdgeInsets.zero,
sliver: SliverList(
delegate: BuildSlivers(
heights: heights,
builder: (context, index) {
return _CacheHeight(
heights: heights,
index: index,
child: children[index],
);
},
),
),
),
],
),
);
}
}
class SecondComponentList extends StatelessWidget {
const SecondComponentList({
super.key,
required this.scaffoldKey,
});
final GlobalKey<ScaffoldState> scaffoldKey;
@override
Widget build(BuildContext context) {
List<Widget> children = [
Navigation(scaffoldKey: scaffoldKey),
colDivider,
const Selection(),
colDivider,
const TextInputs(),
];
List<double?> heights = List.filled(children.length, null);
// Fully traverse this list before moving on.
return FocusTraversalGroup(
child: CustomScrollView(
slivers: [
SliverPadding(
padding: const EdgeInsetsDirectional.only(end: smallSpacing),
sliver: SliverList(
delegate: BuildSlivers(
heights: heights,
builder: (context, index) {
return _CacheHeight(
heights: heights,
index: index,
child: children[index],
);
},
),
),
),
],
),
);
}
}
// If the content of a CustomScrollView does not change, then it's
// safe to cache the heights of each item as they are laid out. The
// sum of the cached heights are returned by an override of
// `SliverChildDelegate.estimateMaxScrollOffset`. The default version
// of this method bases its estimate on the average height of the
// visible items. The override ensures that the scrollbar thumb's
// size, which depends on the max scroll offset, will shrink smoothly
// as the contents of the list are exposed for the first time, and
// then remain fixed.
class _CacheHeight extends SingleChildRenderObjectWidget {
const _CacheHeight({
super.child,
required this.heights,
required this.index,
});
final List<double?> heights;
final int index;
@override
RenderObject createRenderObject(BuildContext context) {
return _RenderCacheHeight(
heights: heights,
index: index,
);
}
@override
void updateRenderObject(
BuildContext context, _RenderCacheHeight renderObject) {
renderObject
..heights = heights
..index = index;
}
}
class _RenderCacheHeight extends RenderProxyBox {
_RenderCacheHeight({
required List<double?> heights,
required int index,
}) : _heights = heights,
_index = index,
super();
List<double?> _heights;
List<double?> get heights => _heights;
set heights(List<double?> value) {
if (value == _heights) {
return;
}
_heights = value;
markNeedsLayout();
}
int _index;
int get index => _index;
set index(int value) {
if (value == index) {
return;
}
_index = value;
markNeedsLayout();
}
@override
void performLayout() {
super.performLayout();
heights[index] = size.height;
}
}
// The heights information is used to override the `estimateMaxScrollOffset` and
// provide a more accurate estimation for the max scroll offset.
class BuildSlivers extends SliverChildBuilderDelegate {
BuildSlivers({
required NullableIndexedWidgetBuilder builder,
required this.heights,
}) : super(builder, childCount: heights.length);
final List<double?> heights;
@override
double? estimateMaxScrollOffset(int firstIndex, int lastIndex,
double leadingScrollOffset, double trailingScrollOffset) {
return heights.reduce((sum, height) => (sum ?? 0) + (height ?? 0))!;
}
}
class Actions extends StatelessWidget {
const Actions({super.key});
@override
Widget build(BuildContext context) {
return const ComponentGroupDecoration(label: 'Actions', children: <Widget>[
Buttons(),
FloatingActionButtons(),
IconToggleButtons(),
SegmentedButtons(),
]);
}
}
class Communication extends StatelessWidget {
const Communication({super.key});
@override
Widget build(BuildContext context) {
return const ComponentGroupDecoration(label: 'Communication', children: [
NavigationBars(
selectedIndex: 1,
isExampleBar: true,
isBadgeExample: true,
),
ProgressIndicators(),
SnackBarSection(),
]);
}
}
class Containment extends StatelessWidget {
const Containment({super.key});
@override
Widget build(BuildContext context) {
return const ComponentGroupDecoration(label: 'Containment', children: [
BottomSheetSection(),
Cards(),
Dialogs(),
Dividers(),
// TODO: Add Lists, https://github.com/flutter/flutter/issues/114006
// TODO: Add Side sheets, https://github.com/flutter/flutter/issues/119328
]);
}
}
class Navigation extends StatelessWidget {
const Navigation({super.key, required this.scaffoldKey});
final GlobalKey<ScaffoldState> scaffoldKey;
@override
Widget build(BuildContext context) {
return ComponentGroupDecoration(label: 'Navigation', children: [
const BottomAppBars(),
const NavigationBars(
selectedIndex: 0,
isExampleBar: true,
),
NavigationDrawers(scaffoldKey: scaffoldKey),
const NavigationRails(),
const Tabs(),
const SearchAnchors(),
const TopAppBars(),
]);
}
}
class Selection extends StatelessWidget {
const Selection({super.key});
@override
Widget build(BuildContext context) {
return const ComponentGroupDecoration(label: 'Selection', children: [
Checkboxes(),
Chips(),
DatePicker(),
TimePicker(),
Menus(),
Radios(),
Sliders(),
Switches(),
]);
}
}
class TextInputs extends StatelessWidget {
const TextInputs({super.key});
@override
Widget build(BuildContext context) {
return const ComponentGroupDecoration(
label: 'Text inputs',
children: [TextFields()],
);
}
}
class Buttons extends StatefulWidget {
const Buttons({super.key});
@override
State<Buttons> createState() => _ButtonsState();
}
class _ButtonsState extends State<Buttons> {
@override
Widget build(BuildContext context) {
return const ComponentDecoration(
label: 'Common buttons',
tooltipMessage:
'Use ElevatedButton, FilledButton, FilledButton.tonal, OutlinedButton, or TextButton',
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ButtonsWithoutIcon(isDisabled: false),
ButtonsWithIcon(),
ButtonsWithoutIcon(isDisabled: true),
],
),
),
);
}
}
class ButtonsWithoutIcon extends StatelessWidget {
final bool isDisabled;
const ButtonsWithoutIcon({super.key, required this.isDisabled});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 5.0),
child: IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ElevatedButton(
onPressed: isDisabled ? null : () {},
child: const Text('Elevated'),
),
colDivider,
FilledButton(
onPressed: isDisabled ? null : () {},
child: const Text('Filled'),
),
colDivider,
FilledButton.tonal(
onPressed: isDisabled ? null : () {},
child: const Text('Filled tonal'),
),
colDivider,
OutlinedButton(
onPressed: isDisabled ? null : () {},
child: const Text('Outlined'),
),
colDivider,
TextButton(
onPressed: isDisabled ? null : () {},
child: const Text('Text'),
),
],
),
),
);
}
}
class ButtonsWithIcon extends StatelessWidget {
const ButtonsWithIcon({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ElevatedButton.icon(
onPressed: () {},
icon: const Icon(Icons.add),
label: const Text('Icon'),
),
colDivider,
FilledButton.icon(
onPressed: () {},
label: const Text('Icon'),
icon: const Icon(Icons.add),
),
colDivider,
FilledButton.tonalIcon(
onPressed: () {},
label: const Text('Icon'),
icon: const Icon(Icons.add),
),
colDivider,
OutlinedButton.icon(
onPressed: () {},
icon: const Icon(Icons.add),
label: const Text('Icon'),
),
colDivider,
TextButton.icon(
onPressed: () {},
icon: const Icon(Icons.add),
label: const Text('Icon'),
)
],
),
),
);
}
}
class FloatingActionButtons extends StatelessWidget {
const FloatingActionButtons({super.key});
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Floating action buttons',
tooltipMessage:
'Use FloatingActionButton or FloatingActionButton.extended',
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
runSpacing: smallSpacing,
spacing: smallSpacing,
children: [
FloatingActionButton.small(
onPressed: () {},
tooltip: 'Small',
child: const Icon(Icons.add),
),
FloatingActionButton.extended(
onPressed: () {},
tooltip: 'Extended',
icon: const Icon(Icons.add),
label: const Text('Create'),
),
FloatingActionButton(
onPressed: () {},
tooltip: 'Standard',
child: const Icon(Icons.add),
),
FloatingActionButton.large(
onPressed: () {},
tooltip: 'Large',
child: const Icon(Icons.add),
),
],
),
);
}
}
class Cards extends StatelessWidget {
const Cards({super.key});
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Cards',
tooltipMessage: 'Use Card',
child: Wrap(
alignment: WrapAlignment.spaceEvenly,
children: [
SizedBox(
width: cardWidth,
child: Card(
child: Container(
padding: const EdgeInsets.fromLTRB(10, 5, 5, 10),
child: Column(
children: [
Align(
alignment: Alignment.topRight,
child: IconButton(
icon: const Icon(Icons.more_vert),
onPressed: () {},
),
),
const SizedBox(height: 20),
const Align(
alignment: Alignment.bottomLeft,
child: Text('Elevated'),
)
],
),
),
),
),
SizedBox(
width: cardWidth,
child: Card(
color: Theme.of(context).colorScheme.surfaceVariant,
elevation: 0,
child: Container(
padding: const EdgeInsets.fromLTRB(10, 5, 5, 10),
child: Column(
children: [
Align(
alignment: Alignment.topRight,
child: IconButton(
icon: const Icon(Icons.more_vert),
onPressed: () {},
),
),
const SizedBox(height: 20),
const Align(
alignment: Alignment.bottomLeft,
child: Text('Filled'),
)
],
),
),
),
),
SizedBox(
width: cardWidth,
child: Card(
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Theme.of(context).colorScheme.outline,
),
borderRadius: const BorderRadius.all(Radius.circular(12)),
),
child: Container(
padding: const EdgeInsets.fromLTRB(10, 5, 5, 10),
child: Column(
children: [
Align(
alignment: Alignment.topRight,
child: IconButton(
icon: const Icon(Icons.more_vert),
onPressed: () {},
),
),
const SizedBox(height: 20),
const Align(
alignment: Alignment.bottomLeft,
child: Text('Outlined'),
)
],
),
),
),
),
],
),
);
}
}
class _ClearButton extends StatelessWidget {
const _ClearButton({required this.controller});
final TextEditingController controller;
@override
Widget build(BuildContext context) => IconButton(
icon: const Icon(Icons.clear),
onPressed: () => controller.clear(),
);
}
class TextFields extends StatefulWidget {
const TextFields({super.key});
@override
State<TextFields> createState() => _TextFieldsState();
}
class _TextFieldsState extends State<TextFields> {
final TextEditingController _controllerFilled = TextEditingController();
final TextEditingController _controllerOutlined = TextEditingController();
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Text fields',
tooltipMessage: 'Use TextField with different InputDecoration',
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(smallSpacing),
child: TextField(
controller: _controllerFilled,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
suffixIcon: _ClearButton(controller: _controllerFilled),
labelText: 'Filled',
hintText: 'hint text',
helperText: 'supporting text',
filled: true,
),
),
),
Padding(
padding: const EdgeInsets.all(smallSpacing),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: SizedBox(
width: 200,
child: TextField(
maxLength: 10,
maxLengthEnforcement: MaxLengthEnforcement.none,
controller: _controllerFilled,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
suffixIcon: _ClearButton(controller: _controllerFilled),
labelText: 'Filled',
hintText: 'hint text',
helperText: 'supporting text',
filled: true,
errorText: 'error text',
),
),
),
),
const SizedBox(width: smallSpacing),
Flexible(
child: SizedBox(
width: 200,
child: TextField(
controller: _controllerFilled,
enabled: false,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
suffixIcon: _ClearButton(controller: _controllerFilled),
labelText: 'Disabled',
hintText: 'hint text',
helperText: 'supporting text',
filled: true,
),
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(smallSpacing),
child: TextField(
controller: _controllerOutlined,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
suffixIcon: _ClearButton(controller: _controllerOutlined),
labelText: 'Outlined',
hintText: 'hint text',
helperText: 'supporting text',
border: const OutlineInputBorder(),
),
),
),
Padding(
padding: const EdgeInsets.all(smallSpacing),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: SizedBox(
width: 200,
child: TextField(
controller: _controllerOutlined,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
suffixIcon:
_ClearButton(controller: _controllerOutlined),
labelText: 'Outlined',
hintText: 'hint text',
helperText: 'supporting text',
errorText: 'error text',
border: const OutlineInputBorder(),
filled: true,
),
),
),
),
const SizedBox(width: smallSpacing),
Flexible(
child: SizedBox(
width: 200,
child: TextField(
controller: _controllerOutlined,
enabled: false,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
suffixIcon:
_ClearButton(controller: _controllerOutlined),
labelText: 'Disabled',
hintText: 'hint text',
helperText: 'supporting text',
border: const OutlineInputBorder(),
filled: true,
),
),
),
),
])),
],
),
);
}
}
class Dialogs extends StatefulWidget {
const Dialogs({super.key});
@override
State<Dialogs> createState() => _DialogsState();
}
class _DialogsState extends State<Dialogs> {
void openDialog(BuildContext context) {
showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: const Text('What is a dialog?'),
content: const Text(
'A dialog is a type of modal window that appears in front of app content to provide critical information, or prompt for a decision to be made.'),
actions: <Widget>[
TextButton(
child: const Text('Dismiss'),
onPressed: () => Navigator.of(context).pop(),
),
FilledButton(
child: const Text('Okay'),
onPressed: () => Navigator.of(context).pop(),
),
],
),
);
}
void openFullscreenDialog(BuildContext context) {
showDialog<void>(
context: context,
builder: (context) => Dialog.fullscreen(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Scaffold(
appBar: AppBar(
title: const Text('Full-screen dialog'),
centerTitle: false,
leading: IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.of(context).pop(),
),
actions: [
TextButton(
child: const Text('Close'),
onPressed: () => Navigator.of(context).pop(),
),
],
),
),
),
),
);
}
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Dialog',
tooltipMessage:
'Use showDialog with Dialog.fullscreen, AlertDialog, or SimpleDialog',
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: [
TextButton(
child: const Text(
'Show dialog',
style: TextStyle(fontWeight: FontWeight.bold),
),
onPressed: () => openDialog(context),
),
TextButton(
child: const Text(
'Show full-screen dialog',
style: TextStyle(fontWeight: FontWeight.bold),
),
onPressed: () => openFullscreenDialog(context),
),
],
),
);
}
}
class Dividers extends StatelessWidget {
const Dividers({super.key});
@override
Widget build(BuildContext context) {
return const ComponentDecoration(
label: 'Dividers',
tooltipMessage: 'Use Divider or VerticalDivider',
child: Column(
children: <Widget>[
Divider(key: Key('divider')),
],
),
);
}
}
class Switches extends StatelessWidget {
const Switches({super.key});
@override
Widget build(BuildContext context) {
return const ComponentDecoration(
label: 'Switches',
tooltipMessage: 'Use SwitchListTile or Switch',
child: Column(
children: <Widget>[
SwitchRow(isEnabled: true),
SwitchRow(isEnabled: false),
],
),
);
}
}
class SwitchRow extends StatefulWidget {
const SwitchRow({super.key, required this.isEnabled});
final bool isEnabled;
@override
State<SwitchRow> createState() => _SwitchRowState();
}
class _SwitchRowState extends State<SwitchRow> {
bool value0 = false;
bool value1 = true;
final MaterialStateProperty<Icon?> thumbIcon =
MaterialStateProperty.resolveWith<Icon?>((states) {
if (states.contains(MaterialState.selected)) {
return const Icon(Icons.check);
}
return const Icon(Icons.close);
});
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
// TODO: use SwitchListTile when thumbIcon is available https://github.com/flutter/flutter/issues/118616
Switch(
value: value0,
onChanged: widget.isEnabled
? (value) {
setState(() {
value0 = value;
});
}
: null,
),
Switch(
thumbIcon: thumbIcon,
value: value1,
onChanged: widget.isEnabled
? (value) {
setState(() {
value1 = value;
});
}
: null,
),
],
);
}
}
class Checkboxes extends StatefulWidget {
const Checkboxes({super.key});
@override
State<Checkboxes> createState() => _CheckboxesState();
}
class _CheckboxesState extends State<Checkboxes> {
bool? isChecked0 = true;
bool? isChecked1;
bool? isChecked2 = false;
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Checkboxes',
tooltipMessage: 'Use CheckboxListTile or Checkbox',
child: Column(
children: <Widget>[
CheckboxListTile(
tristate: true,
value: isChecked0,
title: const Text('Option 1'),
onChanged: (value) {
setState(() {
isChecked0 = value;
});
},
),
CheckboxListTile(
tristate: true,
value: isChecked1,
title: const Text('Option 2'),
onChanged: (value) {
setState(() {
isChecked1 = value;
});
},
),
CheckboxListTile(
tristate: true,
value: isChecked2,
title: const Text('Option 3'),
// TODO: showcase error state https://github.com/flutter/flutter/issues/118616
onChanged: (value) {
setState(() {
isChecked2 = value;
});
},
),
const CheckboxListTile(
tristate: true,
title: Text('Option 4'),
value: true,
onChanged: null,
),
],
),
);
}
}
enum Value { first, second }
class Radios extends StatefulWidget {
const Radios({super.key});
@override
State<Radios> createState() => _RadiosState();
}
enum Options { option1, option2, option3 }
class _RadiosState extends State<Radios> {
Options? _selectedOption = Options.option1;
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Radio buttons',
tooltipMessage: 'Use RadioListTile<T> or Radio<T>',
child: Column(
children: <Widget>[
RadioListTile<Options>(
title: const Text('Option 1'),
value: Options.option1,
groupValue: _selectedOption,
onChanged: (value) {
setState(() {
_selectedOption = value;
});
},
),
RadioListTile<Options>(
title: const Text('Option 2'),
value: Options.option2,
groupValue: _selectedOption,
onChanged: (value) {
setState(() {
_selectedOption = value;
});
},
),
RadioListTile<Options>(
title: const Text('Option 3'),
value: Options.option3,
groupValue: _selectedOption,
onChanged: null,
),
],
),
);
}
}
class ProgressIndicators extends StatefulWidget {
const ProgressIndicators({super.key});
@override
State<ProgressIndicators> createState() => _ProgressIndicatorsState();
}
class _ProgressIndicatorsState extends State<ProgressIndicators> {
bool playProgressIndicator = false;
@override
Widget build(BuildContext context) {
final double? progressValue = playProgressIndicator ? null : 0.7;
return ComponentDecoration(
label: 'Progress indicators',
tooltipMessage:
'Use CircularProgressIndicator or LinearProgressIndicator',
child: Column(
children: <Widget>[
Row(
children: [
IconButton(
isSelected: playProgressIndicator,
selectedIcon: const Icon(Icons.pause),
icon: const Icon(Icons.play_arrow),
onPressed: () {
setState(() {
playProgressIndicator = !playProgressIndicator;
});
},
),
Expanded(
child: Row(
children: <Widget>[
rowDivider,
CircularProgressIndicator(
value: progressValue,
),
rowDivider,
Expanded(
child: LinearProgressIndicator(
value: progressValue,
),
),
rowDivider,
],
),
),
],
),
],
),
);
}
}
const List<NavigationDestination> appBarDestinations = [
NavigationDestination(
tooltip: '',
icon: Icon(Icons.widgets_outlined),
label: 'Components',
selectedIcon: Icon(Icons.widgets),
),
NavigationDestination(
tooltip: '',
icon: Icon(Icons.format_paint_outlined),
label: 'Color',
selectedIcon: Icon(Icons.format_paint),
),
NavigationDestination(
tooltip: '',
icon: Icon(Icons.text_snippet_outlined),
label: 'Typography',
selectedIcon: Icon(Icons.text_snippet),
),
NavigationDestination(
tooltip: '',
icon: Icon(Icons.invert_colors_on_outlined),
label: 'Elevation',
selectedIcon: Icon(Icons.opacity),
)
];
const List<Widget> exampleBarDestinations = [
NavigationDestination(
tooltip: '',
icon: Icon(Icons.explore_outlined),
label: 'Explore',
selectedIcon: Icon(Icons.explore),
),
NavigationDestination(
tooltip: '',
icon: Icon(Icons.pets_outlined),
label: 'Pets',
selectedIcon: Icon(Icons.pets),
),
NavigationDestination(
tooltip: '',
icon: Icon(Icons.account_box_outlined),
label: 'Account',
selectedIcon: Icon(Icons.account_box),
)
];
List<Widget> barWithBadgeDestinations = [
NavigationDestination(
tooltip: '',
icon: Badge.count(count: 1000, child: const Icon(Icons.mail_outlined)),
label: 'Mail',
selectedIcon: Badge.count(count: 1000, child: const Icon(Icons.mail)),
),
const NavigationDestination(
tooltip: '',
icon: Badge(label: Text('10'), child: Icon(Icons.chat_bubble_outline)),
label: 'Chat',
selectedIcon: Badge(label: Text('10'), child: Icon(Icons.chat_bubble)),
),
const NavigationDestination(
tooltip: '',
icon: Badge(child: Icon(Icons.group_outlined)),
label: 'Rooms',
selectedIcon: Badge(child: Icon(Icons.group_rounded)),
),
NavigationDestination(
tooltip: '',
icon: Badge.count(count: 3, child: const Icon(Icons.videocam_outlined)),
label: 'Meet',
selectedIcon: Badge.count(count: 3, child: const Icon(Icons.videocam)),
)
];
class NavigationBars extends StatefulWidget {
const NavigationBars({
super.key,
this.onSelectItem,
required this.selectedIndex,
required this.isExampleBar,
this.isBadgeExample = false,
});
final void Function(int)? onSelectItem;
final int selectedIndex;
final bool isExampleBar;
final bool isBadgeExample;
@override
State<NavigationBars> createState() => _NavigationBarsState();
}
class _NavigationBarsState extends State<NavigationBars> {
late int selectedIndex;
@override
void initState() {
super.initState();
selectedIndex = widget.selectedIndex;
}
@override
void didUpdateWidget(covariant NavigationBars oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.selectedIndex != oldWidget.selectedIndex) {
selectedIndex = widget.selectedIndex;
}
}
@override
Widget build(BuildContext context) {
// App NavigationBar should get first focus.
Widget navigationBar = Focus(
autofocus: !(widget.isExampleBar || widget.isBadgeExample),
child: NavigationBar(
selectedIndex: selectedIndex,
onDestinationSelected: (index) {
setState(() {
selectedIndex = index;
});
if (!widget.isExampleBar) widget.onSelectItem!(index);
},
destinations: widget.isExampleBar && widget.isBadgeExample
? barWithBadgeDestinations
: widget.isExampleBar
? exampleBarDestinations
: appBarDestinations,
),
);
if (widget.isExampleBar && widget.isBadgeExample) {
navigationBar = ComponentDecoration(
label: 'Badges',
tooltipMessage: 'Use Badge or Badge.count',
child: navigationBar);
} else if (widget.isExampleBar) {
navigationBar = ComponentDecoration(
label: 'Navigation bar',
tooltipMessage: 'Use NavigationBar',
child: navigationBar);
}
return navigationBar;
}
}
class IconToggleButtons extends StatefulWidget {
const IconToggleButtons({super.key});
@override
State<IconToggleButtons> createState() => _IconToggleButtonsState();
}
class _IconToggleButtonsState extends State<IconToggleButtons> {
bool standardSelected = false;
bool filledSelected = false;
bool tonalSelected = false;
bool outlinedSelected = false;
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Icon buttons',
tooltipMessage:
'Use IconButton, IconButton.filled, IconButton.filledTonal, and IconButton.outlined',
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Column(
// Standard IconButton
children: <Widget>[
IconButton(
isSelected: standardSelected,
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
onPressed: () {
setState(() {
standardSelected = !standardSelected;
});
},
),
colDivider,
IconButton(
isSelected: standardSelected,
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
onPressed: null,
),
],
),
Column(
children: <Widget>[
// Filled IconButton
IconButton.filled(
isSelected: filledSelected,
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
onPressed: () {
setState(() {
filledSelected = !filledSelected;
});
},
),
colDivider,
IconButton.filled(
isSelected: filledSelected,
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
onPressed: null,
),
],
),
Column(
children: <Widget>[
// Filled Tonal IconButton
IconButton.filledTonal(
isSelected: tonalSelected,
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
onPressed: () {
setState(() {
tonalSelected = !tonalSelected;
});
},
),
colDivider,
IconButton.filledTonal(
isSelected: tonalSelected,
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
onPressed: null,
),
],
),
Column(
children: <Widget>[
// Outlined IconButton
IconButton.outlined(
isSelected: outlinedSelected,
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
onPressed: () {
setState(() {
outlinedSelected = !outlinedSelected;
});
},
),
colDivider,
IconButton.outlined(
isSelected: outlinedSelected,
icon: const Icon(Icons.settings_outlined),
selectedIcon: const Icon(Icons.settings),
onPressed: null,
),
],
),
],
),
);
}
}
class Chips extends StatefulWidget {
const Chips({super.key});
@override
State<Chips> createState() => _ChipsState();
}
class _ChipsState extends State<Chips> {
bool isFiltered = true;
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Chips',
tooltipMessage:
'Use ActionChip, FilterChip, or InputChip. \nActionChip can also be used for suggestion chip',
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Wrap(
spacing: smallSpacing,
runSpacing: smallSpacing,
children: <Widget>[
ActionChip(
label: const Text('Assist'),
avatar: const Icon(Icons.event),
onPressed: () {},
),
FilterChip(
label: const Text('Filter'),
selected: isFiltered,
onSelected: (selected) {
setState(() => isFiltered = selected);
},
),
InputChip(
label: const Text('Input'),
onPressed: () {},
onDeleted: () {},
),
ActionChip(
label: const Text('Suggestion'),
onPressed: () {},
),
],
),
colDivider,
Wrap(
spacing: smallSpacing,
runSpacing: smallSpacing,
children: <Widget>[
const ActionChip(
label: Text('Assist'),
avatar: Icon(Icons.event),
),
FilterChip(
label: const Text('Filter'),
selected: isFiltered,
onSelected: null,
),
InputChip(
label: const Text('Input'),
onDeleted: () {},
isEnabled: false,
),
const ActionChip(
label: Text('Suggestion'),
),
],
),
],
),
);
}
}
class DatePicker extends StatefulWidget {
const DatePicker({super.key});
@override
State<DatePicker> createState() => _DatePickerState();
}
class _DatePickerState extends State<DatePicker> {
DateTime? selectedDate;
final DateTime _firstDate = DateTime(DateTime.now().year - 2);
final DateTime _lastDate = DateTime(DateTime.now().year + 1);
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Date picker',
tooltipMessage: 'Use showDatePicker',
child: TextButton.icon(
onPressed: () async {
DateTime? date = await showDatePicker(
context: context,
initialDate: selectedDate ?? DateTime.now(),
firstDate: _firstDate,
lastDate: _lastDate,
);
setState(() {
selectedDate = date;
if (selectedDate != null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
'Selected Date: ${selectedDate!.day}/${selectedDate!.month}/${selectedDate!.year}'),
));
}
});
},
icon: const Icon(Icons.calendar_month),
label: const Text(
'Show date picker',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
);
}
}
class TimePicker extends StatefulWidget {
const TimePicker({super.key});
@override
State<TimePicker> createState() => _TimePickerState();
}
class _TimePickerState extends State<TimePicker> {
TimeOfDay? selectedTime;
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Time picker',
tooltipMessage: 'Use showTimePicker',
child: TextButton.icon(
onPressed: () async {
final TimeOfDay? time = await showTimePicker(
context: context,
initialTime: selectedTime ?? TimeOfDay.now(),
builder: (context, child) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(
alwaysUse24HourFormat: true,
),
child: child!,
);
},
);
setState(() {
selectedTime = time;
if (selectedTime != null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content:
Text('Selected time: ${selectedTime!.format(context)}'),
));
}
});
},
icon: const Icon(Icons.schedule),
label: const Text(
'Show time picker',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
);
}
}
class SegmentedButtons extends StatelessWidget {
const SegmentedButtons({super.key});
@override
Widget build(BuildContext context) {
return const ComponentDecoration(
label: 'Segmented buttons',
tooltipMessage: 'Use SegmentedButton<T>',
child: Column(
children: <Widget>[
SingleChoice(),
colDivider,
MultipleChoice(),
],
),
);
}
}
enum Calendar { day, week, month, year }
class SingleChoice extends StatefulWidget {
const SingleChoice({super.key});
@override
State<SingleChoice> createState() => _SingleChoiceState();
}
class _SingleChoiceState extends State<SingleChoice> {
Calendar calendarView = Calendar.day;
@override
Widget build(BuildContext context) {
return SegmentedButton<Calendar>(
segments: const <ButtonSegment<Calendar>>[
ButtonSegment<Calendar>(
value: Calendar.day,
label: Text('Day'),
icon: Icon(Icons.calendar_view_day)),
ButtonSegment<Calendar>(
value: Calendar.week,
label: Text('Week'),
icon: Icon(Icons.calendar_view_week)),
ButtonSegment<Calendar>(
value: Calendar.month,
label: Text('Month'),
icon: Icon(Icons.calendar_view_month)),
ButtonSegment<Calendar>(
value: Calendar.year,
label: Text('Year'),
icon: Icon(Icons.calendar_today)),
],
selected: <Calendar>{calendarView},
onSelectionChanged: (newSelection) {
setState(() {
// By default there is only a single segment that can be
// selected at one time, so its value is always the first
// item in the selected set.
calendarView = newSelection.first;
});
},
);
}
}
enum Sizes { extraSmall, small, medium, large, extraLarge }
class MultipleChoice extends StatefulWidget {
const MultipleChoice({super.key});
@override
State<MultipleChoice> createState() => _MultipleChoiceState();
}
class _MultipleChoiceState extends State<MultipleChoice> {
Set<Sizes> selection = <Sizes>{Sizes.large, Sizes.extraLarge};
@override
Widget build(BuildContext context) {
return SegmentedButton<Sizes>(
segments: const <ButtonSegment<Sizes>>[
ButtonSegment<Sizes>(value: Sizes.extraSmall, label: Text('XS')),
ButtonSegment<Sizes>(value: Sizes.small, label: Text('S')),
ButtonSegment<Sizes>(value: Sizes.medium, label: Text('M')),
ButtonSegment<Sizes>(
value: Sizes.large,
label: Text('L'),
),
ButtonSegment<Sizes>(value: Sizes.extraLarge, label: Text('XL')),
],
selected: selection,
onSelectionChanged: (newSelection) {
setState(() {
selection = newSelection;
});
},
multiSelectionEnabled: true,
);
}
}
class SnackBarSection extends StatelessWidget {
const SnackBarSection({super.key});
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Snackbar',
tooltipMessage:
'Use ScaffoldMessenger.of(context).showSnackBar with SnackBar',
child: TextButton(
onPressed: () {
final snackBar = SnackBar(
behavior: SnackBarBehavior.floating,
width: 400.0,
content: const Text('This is a snackbar'),
action: SnackBarAction(
label: 'Close',
onPressed: () {},
),
);
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
child: const Text(
'Show snackbar',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
);
}
}
class BottomSheetSection extends StatefulWidget {
const BottomSheetSection({super.key});
@override
State<BottomSheetSection> createState() => _BottomSheetSectionState();
}
class _BottomSheetSectionState extends State<BottomSheetSection> {
bool isNonModalBottomSheetOpen = false;
PersistentBottomSheetController? _nonModalBottomSheetController;
@override
Widget build(BuildContext context) {
List<Widget> buttonList = <Widget>[
IconButton(onPressed: () {}, icon: const Icon(Icons.share_outlined)),
IconButton(onPressed: () {}, icon: const Icon(Icons.add)),
IconButton(onPressed: () {}, icon: const Icon(Icons.delete_outline)),
IconButton(onPressed: () {}, icon: const Icon(Icons.archive_outlined)),
IconButton(onPressed: () {}, icon: const Icon(Icons.settings_outlined)),
IconButton(onPressed: () {}, icon: const Icon(Icons.favorite_border)),
];
List<Text> labelList = const <Text>[
Text('Share'),
Text('Add to'),
Text('Trash'),
Text('Archive'),
Text('Settings'),
Text('Favorite')
];
buttonList = List.generate(
buttonList.length,
(index) => Padding(
padding: const EdgeInsets.fromLTRB(20.0, 30.0, 20.0, 20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
buttonList[index],
labelList[index],
],
),
));
return ComponentDecoration(
label: 'Bottom sheet',
tooltipMessage: 'Use showModalBottomSheet<T> or showBottomSheet<T>',
child: Wrap(
alignment: WrapAlignment.spaceEvenly,
children: [
TextButton(
child: const Text(
'Show modal bottom sheet',
style: TextStyle(fontWeight: FontWeight.bold),
),
onPressed: () {
showModalBottomSheet<void>(
showDragHandle: true,
context: context,
// TODO: Remove when this is in the framework https://github.com/flutter/flutter/issues/118619
constraints: const BoxConstraints(maxWidth: 640),
builder: (context) {
return SizedBox(
height: 150,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
children: buttonList,
),
),
);
},
);
},
),
TextButton(
child: Text(
isNonModalBottomSheetOpen
? 'Hide bottom sheet'
: 'Show bottom sheet',
style: const TextStyle(fontWeight: FontWeight.bold),
),
onPressed: () {
if (isNonModalBottomSheetOpen) {
_nonModalBottomSheetController?.close();
setState(() {
isNonModalBottomSheetOpen = false;
});
return;
} else {
setState(() {
isNonModalBottomSheetOpen = true;
});
}
_nonModalBottomSheetController = showBottomSheet(
elevation: 8.0,
context: context,
// TODO: Remove when this is in the framework https://github.com/flutter/flutter/issues/118619
constraints: const BoxConstraints(maxWidth: 640),
builder: (context) {
return SizedBox(
height: 150,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
children: buttonList,
),
),
);
},
);
},
),
],
),
);
}
}
class BottomAppBars extends StatelessWidget {
const BottomAppBars({super.key});
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Bottom app bar',
tooltipMessage: 'Use BottomAppBar',
child: Column(
children: [
SizedBox(
height: 80,
child: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {},
elevation: 0.0,
child: const Icon(Icons.add),
),
floatingActionButtonLocation:
FloatingActionButtonLocation.endContained,
bottomNavigationBar: BottomAppBar(
child: Row(
children: <Widget>[
const IconButtonAnchorExample(),
IconButton(
tooltip: 'Search',
icon: const Icon(Icons.search),
onPressed: () {},
),
IconButton(
tooltip: 'Favorite',
icon: const Icon(Icons.favorite),
onPressed: () {},
),
],
),
),
),
),
],
),
);
}
}
class IconButtonAnchorExample extends StatelessWidget {
const IconButtonAnchorExample({super.key});
@override
Widget build(BuildContext context) {
return MenuAnchor(
builder: (context, controller, child) {
return IconButton(
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
},
icon: const Icon(Icons.more_vert),
);
},
menuChildren: [
MenuItemButton(
child: const Text('Menu 1'),
onPressed: () {},
),
MenuItemButton(
child: const Text('Menu 2'),
onPressed: () {},
),
SubmenuButton(
menuChildren: <Widget>[
MenuItemButton(
onPressed: () {},
child: const Text('Menu 3.1'),
),
MenuItemButton(
onPressed: () {},
child: const Text('Menu 3.2'),
),
MenuItemButton(
onPressed: () {},
child: const Text('Menu 3.3'),
),
],
child: const Text('Menu 3'),
),
],
);
}
}
class ButtonAnchorExample extends StatelessWidget {
const ButtonAnchorExample({super.key});
@override
Widget build(BuildContext context) {
return MenuAnchor(
builder: (context, controller, child) {
return FilledButton.tonal(
onPressed: () {
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
},
child: const Text('Show menu'),
);
},
menuChildren: [
MenuItemButton(
leadingIcon: const Icon(Icons.people_alt_outlined),
child: const Text('Item 1'),
onPressed: () {},
),
MenuItemButton(
leadingIcon: const Icon(Icons.remove_red_eye_outlined),
child: const Text('Item 2'),
onPressed: () {},
),
MenuItemButton(
leadingIcon: const Icon(Icons.refresh),
onPressed: () {},
child: const Text('Item 3'),
),
],
);
}
}
class NavigationDrawers extends StatelessWidget {
const NavigationDrawers({super.key, required this.scaffoldKey});
final GlobalKey<ScaffoldState> scaffoldKey;
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Navigation drawer',
tooltipMessage:
'Use NavigationDrawer. For modal navigation drawers, see Scaffold.endDrawer',
child: Column(
children: [
const SizedBox(height: 520, child: NavigationDrawerSection()),
colDivider,
colDivider,
TextButton(
child: const Text('Show modal navigation drawer',
style: TextStyle(fontWeight: FontWeight.bold)),
onPressed: () {
scaffoldKey.currentState!.openEndDrawer();
},
),
],
),
);
}
}
class NavigationDrawerSection extends StatefulWidget {
const NavigationDrawerSection({super.key});
@override
State<NavigationDrawerSection> createState() =>
_NavigationDrawerSectionState();
}
class _NavigationDrawerSectionState extends State<NavigationDrawerSection> {
int navDrawerIndex = 0;
@override
Widget build(BuildContext context) {
return NavigationDrawer(
onDestinationSelected: (selectedIndex) {
setState(() {
navDrawerIndex = selectedIndex;
});
},
selectedIndex: navDrawerIndex,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(28, 16, 16, 10),
child: Text(
'Mail',
style: Theme.of(context).textTheme.titleSmall,
),
),
...destinations.map((destination) {
return NavigationDrawerDestination(
label: Text(destination.label),
icon: destination.icon,
selectedIcon: destination.selectedIcon,
);
}),
const Divider(indent: 28, endIndent: 28),
Padding(
padding: const EdgeInsets.fromLTRB(28, 16, 16, 10),
child: Text(
'Labels',
style: Theme.of(context).textTheme.titleSmall,
),
),
...labelDestinations.map((destination) {
return NavigationDrawerDestination(
label: Text(destination.label),
icon: destination.icon,
selectedIcon: destination.selectedIcon,
);
}),
],
);
}
}
class ExampleDestination {
const ExampleDestination(this.label, this.icon, this.selectedIcon);
final String label;
final Widget icon;
final Widget selectedIcon;
}
const List<ExampleDestination> destinations = <ExampleDestination>[
ExampleDestination('Inbox', Icon(Icons.inbox_outlined), Icon(Icons.inbox)),
ExampleDestination('Outbox', Icon(Icons.send_outlined), Icon(Icons.send)),
ExampleDestination(
'Favorites', Icon(Icons.favorite_outline), Icon(Icons.favorite)),
ExampleDestination('Trash', Icon(Icons.delete_outline), Icon(Icons.delete)),
];
const List<ExampleDestination> labelDestinations = <ExampleDestination>[
ExampleDestination(
'Family', Icon(Icons.bookmark_border), Icon(Icons.bookmark)),
ExampleDestination(
'School', Icon(Icons.bookmark_border), Icon(Icons.bookmark)),
ExampleDestination('Work', Icon(Icons.bookmark_border), Icon(Icons.bookmark)),
];
class NavigationRails extends StatelessWidget {
const NavigationRails({super.key});
@override
Widget build(BuildContext context) {
return const ComponentDecoration(
label: 'Navigation rail',
tooltipMessage: 'Use NavigationRail',
child: IntrinsicWidth(
child: SizedBox(height: 420, child: NavigationRailSection())),
);
}
}
class NavigationRailSection extends StatefulWidget {
const NavigationRailSection({super.key});
@override
State<NavigationRailSection> createState() => _NavigationRailSectionState();
}
class _NavigationRailSectionState extends State<NavigationRailSection> {
int navRailIndex = 0;
@override
Widget build(BuildContext context) {
return NavigationRail(
onDestinationSelected: (selectedIndex) {
setState(() {
navRailIndex = selectedIndex;
});
},
elevation: 4,
leading: FloatingActionButton(
child: const Icon(Icons.create), onPressed: () {}),
groupAlignment: 0.0,
selectedIndex: navRailIndex,
labelType: NavigationRailLabelType.selected,
destinations: <NavigationRailDestination>[
...destinations.map((destination) {
return NavigationRailDestination(
label: Text(destination.label),
icon: destination.icon,
selectedIcon: destination.selectedIcon,
);
}),
],
);
}
}
class Tabs extends StatefulWidget {
const Tabs({super.key});
@override
State<Tabs> createState() => _TabsState();
}
class _TabsState extends State<Tabs> with TickerProviderStateMixin {
late TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
}
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Tabs',
tooltipMessage: 'Use TabBar',
child: SizedBox(
height: 80,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
controller: _tabController,
tabs: const <Widget>[
Tab(
icon: Icon(Icons.videocam_outlined),
text: 'Video',
iconMargin: EdgeInsets.only(bottom: 0.0),
),
Tab(
icon: Icon(Icons.photo_outlined),
text: 'Photos',
iconMargin: EdgeInsets.only(bottom: 0.0),
),
Tab(
icon: Icon(Icons.audiotrack_sharp),
text: 'Audio',
iconMargin: EdgeInsets.only(bottom: 0.0),
),
],
),
// TODO: Showcase secondary tab bar https://github.com/flutter/flutter/issues/111962
),
),
),
);
}
}
class TopAppBars extends StatelessWidget {
const TopAppBars({super.key});
static final actions = [
IconButton(icon: const Icon(Icons.attach_file), onPressed: () {}),
IconButton(icon: const Icon(Icons.event), onPressed: () {}),
IconButton(icon: const Icon(Icons.more_vert), onPressed: () {}),
];
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Top app bars',
tooltipMessage:
'Use AppBar, SliverAppBar, SliverAppBar.medium, or SliverAppBar.large',
child: Column(
children: [
AppBar(
title: const Text('Center-aligned'),
leading: const BackButton(),
actions: [
IconButton(
iconSize: 32,
icon: const Icon(Icons.account_circle_outlined),
onPressed: () {},
),
],
centerTitle: true,
),
colDivider,
AppBar(
title: const Text('Small'),
leading: const BackButton(),
actions: actions,
centerTitle: false,
),
colDivider,
SizedBox(
height: 100,
child: CustomScrollView(
slivers: [
SliverAppBar.medium(
title: const Text('Medium'),
leading: const BackButton(),
actions: actions,
),
const SliverFillRemaining(),
],
),
),
colDivider,
SizedBox(
height: 130,
child: CustomScrollView(
slivers: [
SliverAppBar.large(
title: const Text('Large'),
leading: const BackButton(),
actions: actions,
),
const SliverFillRemaining(),
],
),
),
],
),
);
}
}
class Menus extends StatefulWidget {
const Menus({super.key});
@override
State<Menus> createState() => _MenusState();
}
class _MenusState extends State<Menus> {
final TextEditingController colorController = TextEditingController();
final TextEditingController iconController = TextEditingController();
IconLabel? selectedIcon = IconLabel.smile;
ColorLabel? selectedColor;
@override
Widget build(BuildContext context) {
final List<DropdownMenuEntry<ColorLabel>> colorEntries =
<DropdownMenuEntry<ColorLabel>>[];
for (final ColorLabel color in ColorLabel.values) {
colorEntries.add(DropdownMenuEntry<ColorLabel>(
value: color, label: color.label, enabled: color.label != 'Grey'));
}
final List<DropdownMenuEntry<IconLabel>> iconEntries =
<DropdownMenuEntry<IconLabel>>[];
for (final IconLabel icon in IconLabel.values) {
iconEntries
.add(DropdownMenuEntry<IconLabel>(value: icon, label: icon.label));
}
return ComponentDecoration(
label: 'Menus',
tooltipMessage: 'Use MenuAnchor or DropdownMenu<T>',
child: Column(
children: [
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ButtonAnchorExample(),
rowDivider,
IconButtonAnchorExample(),
],
),
colDivider,
Wrap(
alignment: WrapAlignment.spaceAround,
runAlignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: smallSpacing,
runSpacing: smallSpacing,
children: [
DropdownMenu<ColorLabel>(
controller: colorController,
label: const Text('Color'),
enableFilter: true,
dropdownMenuEntries: colorEntries,
inputDecorationTheme: const InputDecorationTheme(filled: true),
onSelected: (color) {
setState(() {
selectedColor = color;
});
},
),
DropdownMenu<IconLabel>(
initialSelection: IconLabel.smile,
controller: iconController,
leadingIcon: const Icon(Icons.search),
label: const Text('Icon'),
dropdownMenuEntries: iconEntries,
onSelected: (icon) {
setState(() {
selectedIcon = icon;
});
},
),
Icon(
selectedIcon?.icon,
color: selectedColor?.color ?? Colors.grey.withOpacity(0.5),
)
],
),
],
),
);
}
}
enum ColorLabel {
blue('Blue', Colors.blue),
pink('Pink', Colors.pink),
green('Green', Colors.green),
yellow('Yellow', Colors.yellow),
grey('Grey', Colors.grey);
const ColorLabel(this.label, this.color);
final String label;
final Color color;
}
enum IconLabel {
smile('Smile', Icons.sentiment_satisfied_outlined),
cloud(
'Cloud',
Icons.cloud_outlined,
),
brush('Brush', Icons.brush_outlined),
heart('Heart', Icons.favorite);
const IconLabel(this.label, this.icon);
final String label;
final IconData icon;
}
class Sliders extends StatefulWidget {
const Sliders({super.key});
@override
State<Sliders> createState() => _SlidersState();
}
class _SlidersState extends State<Sliders> {
double sliderValue0 = 30.0;
double sliderValue1 = 20.0;
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Sliders',
tooltipMessage: 'Use Slider or RangeSlider',
child: Column(
children: <Widget>[
Slider(
max: 100,
value: sliderValue0,
onChanged: (value) {
setState(() {
sliderValue0 = value;
});
},
),
const SizedBox(height: 20),
Slider(
max: 100,
divisions: 5,
value: sliderValue1,
label: sliderValue1.round().toString(),
onChanged: (value) {
setState(() {
sliderValue1 = value;
});
},
),
],
));
}
}
class SearchAnchors extends StatefulWidget {
const SearchAnchors({super.key});
@override
State<SearchAnchors> createState() => _SearchAnchorsState();
}
class _SearchAnchorsState extends State<SearchAnchors> {
String? selectedColor;
List<ColorItem> searchHistory = <ColorItem>[];
Iterable<Widget> getHistoryList(SearchController controller) {
return searchHistory.map((color) => ListTile(
leading: const Icon(Icons.history),
title: Text(color.label),
trailing: IconButton(
icon: const Icon(Icons.call_missed),
onPressed: () {
controller.text = color.label;
controller.selection =
TextSelection.collapsed(offset: controller.text.length);
}),
onTap: () {
controller.closeView(color.label);
handleSelection(color);
},
));
}
Iterable<Widget> getSuggestions(SearchController controller) {
final String input = controller.value.text;
return ColorItem.values
.where((color) => color.label.contains(input))
.map((filteredColor) => ListTile(
leading: CircleAvatar(backgroundColor: filteredColor.color),
title: Text(filteredColor.label),
trailing: IconButton(
icon: const Icon(Icons.call_missed),
onPressed: () {
controller.text = filteredColor.label;
controller.selection =
TextSelection.collapsed(offset: controller.text.length);
}),
onTap: () {
controller.closeView(filteredColor.label);
handleSelection(filteredColor);
},
));
}
void handleSelection(ColorItem color) {
setState(() {
selectedColor = color.label;
if (searchHistory.length >= 5) {
searchHistory.removeLast();
}
searchHistory.insert(0, color);
});
}
@override
Widget build(BuildContext context) {
return ComponentDecoration(
label: 'Search',
tooltipMessage: 'Use SearchAnchor or SearchAnchor.bar',
child: Column(
children: <Widget>[
SearchAnchor.bar(
barHintText: 'Search colors',
suggestionsBuilder: (context, controller) {
if (controller.text.isEmpty) {
if (searchHistory.isNotEmpty) {
return getHistoryList(controller);
}
return <Widget>[
const Center(
child: Text('No search history.',
style: TextStyle(color: Colors.grey)),
)
];
}
return getSuggestions(controller);
},
),
const SizedBox(height: 20),
if (selectedColor == null)
const Text('Select a color')
else
Text('Last selected color is $selectedColor')
],
),
);
}
}
class ComponentDecoration extends StatefulWidget {
const ComponentDecoration({
super.key,
required this.label,
required this.child,
this.tooltipMessage = '',
});
final String label;
final Widget child;
final String? tooltipMessage;
@override
State<ComponentDecoration> createState() => _ComponentDecorationState();
}
class _ComponentDecorationState extends State<ComponentDecoration> {
final focusNode = FocusNode();
@override
Widget build(BuildContext context) {
return RepaintBoundary(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: smallSpacing),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(widget.label,
style: Theme.of(context).textTheme.titleSmall),
Tooltip(
message: widget.tooltipMessage,
child: const Padding(
padding: EdgeInsets.symmetric(horizontal: 5.0),
child: Icon(Icons.info_outline, size: 16)),
),
],
),
ConstrainedBox(
constraints:
const BoxConstraints.tightFor(width: widthConstraint),
// Tapping within the a component card should request focus
// for that component's children.
child: Focus(
focusNode: focusNode,
canRequestFocus: true,
child: GestureDetector(
onTapDown: (_) {
focusNode.requestFocus();
},
behavior: HitTestBehavior.opaque,
child: Card(
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Theme.of(context).colorScheme.outlineVariant,
),
borderRadius: const BorderRadius.all(Radius.circular(12)),
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 5.0, vertical: 20.0),
child: Center(
child: widget.child,
),
),
),
),
),
),
],
),
),
);
}
}
class ComponentGroupDecoration extends StatelessWidget {
const ComponentGroupDecoration(
{super.key, required this.label, required this.children});
final String label;
final List<Widget> children;
@override
Widget build(BuildContext context) {
// Fully traverse this component group before moving on
return FocusTraversalGroup(
child: Card(
margin: EdgeInsets.zero,
elevation: 0,
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 20.0),
child: Center(
child: Column(
children: [
Text(label, style: Theme.of(context).textTheme.titleLarge),
colDivider,
...children
],
),
),
),
),
);
}
}
enum ColorItem {
red('red', Colors.red),
orange('orange', Colors.orange),
yellow('yellow', Colors.yellow),
green('green', Colors.green),
blue('blue', Colors.blue),
indigo('indigo', Colors.indigo),
violet('violet', Color(0xFF8F00FF)),
purple('purple', Colors.purple),
pink('pink', Colors.pink),
silver('silver', Color(0xFF808080)),
gold('gold', Color(0xFFFFD700)),
beige('beige', Color(0xFFF5F5DC)),
brown('brown', Colors.brown),
grey('grey', Colors.grey),
black('black', Colors.black),
white('white', Colors.white);
const ColorItem(this.label, this.color);
final String label;
final Color color;
}
| samples/material_3_demo/lib/component_screen.dart/0 | {
"file_path": "samples/material_3_demo/lib/component_screen.dart",
"repo_id": "samples",
"token_count": 36204
} | 1,410 |
// 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.
// ignore_for_file: avoid_types_on_closure_parameters
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_3_demo/main.dart';
import 'package:material_3_demo/typography_screen.dart';
import 'component_screen_test.dart';
void main() {
testWidgets(
'Typography screen shows correctly when the corresponding icon is '
'selected on NavigationBar', (tester) async {
widgetSetup(tester, 449);
addTearDown(tester.view.resetPhysicalSize);
await tester.pumpWidget(const App());
expect(find.text('Display Large'), findsNothing);
expect(find.byType(NavigationBar), findsOneWidget);
Finder textIconOnBar = find.descendant(
of: find.byType(NavigationBar),
matching: find.byIcon(Icons.text_snippet_outlined));
expect(textIconOnBar, findsOneWidget);
await tester.tap(textIconOnBar);
await tester.pumpAndSettle(const Duration(microseconds: 500));
expect(textIconOnBar, findsNothing);
Finder selectedTextIconOnBar = find.descendant(
of: find.byType(NavigationBar),
matching: find.byIcon(Icons.text_snippet));
expect(selectedTextIconOnBar, findsOneWidget);
expect(find.text('Display Large'), findsOneWidget);
});
testWidgets(
'Typography screen shows correctly when the corresponding icon is '
'selected on NavigationRail', (tester) async {
widgetSetup(
tester, 1200); // NavigationRail shows only when width is > 1000.
addTearDown(tester.view.resetPhysicalSize);
await tester.pumpWidget(const App());
expect(find.text('Display Large'), findsNothing);
Finder textIconOnRail = find.descendant(
of: find.byType(NavigationRail),
matching: find.byIcon(Icons.text_snippet_outlined));
expect(textIconOnRail, findsOneWidget);
await tester.tap(textIconOnRail);
await tester.pumpAndSettle(const Duration(microseconds: 500));
expect(textIconOnRail, findsNothing);
Finder selectedTextIconOnRail = find.descendant(
of: find.byType(NavigationRail),
matching: find.byIcon(Icons.text_snippet));
expect(selectedTextIconOnRail, findsOneWidget);
expect(find.text('Display Large'), findsOneWidget);
});
testWidgets('Typography screen shows correct content', (tester) async {
await tester.pumpWidget(const MaterialApp(
home: Scaffold(body: Row(children: [TypographyScreen()])),
));
expect(find.text('Display Large'), findsOneWidget);
expect(find.text('Display Medium'), findsOneWidget);
expect(find.text('Display Small'), findsOneWidget);
expect(find.text('Headline Large'), findsOneWidget);
expect(find.text('Headline Medium'), findsOneWidget);
expect(find.text('Headline Small'), findsOneWidget);
expect(find.text('Title Large'), findsOneWidget);
expect(find.text('Title Medium'), findsOneWidget);
expect(find.text('Title Small'), findsOneWidget);
await tester.scrollUntilVisible(
find.text('Body Small'),
500.0,
);
expect(find.text('Label Large'), findsOneWidget);
expect(find.text('Label Medium'), findsOneWidget);
expect(find.text('Label Small'), findsOneWidget);
expect(find.text('Body Large'), findsOneWidget);
expect(find.text('Body Medium'), findsOneWidget);
expect(find.text('Body Small'), findsOneWidget);
expect(find.byType(TextStyleExample), findsNWidgets(15));
});
}
| samples/material_3_demo/test/typography_screen_test.dart/0 | {
"file_path": "samples/material_3_demo/test/typography_screen_test.dart",
"repo_id": "samples",
"token_count": 1230
} | 1,411 |
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'author.dart';
import 'book.dart';
final libraryInstance = Library()
..addBook(
title: 'Left Hand of Darkness',
authorName: 'Ursula K. Le Guin',
isPopular: true,
isNew: true)
..addBook(
title: 'Too Like the Lightning',
authorName: 'Ada Palmer',
isPopular: false,
isNew: true)
..addBook(
title: 'Kindred',
authorName: 'Octavia E. Butler',
isPopular: true,
isNew: false)
..addBook(
title: 'The Lathe of Heaven',
authorName: 'Ursula K. Le Guin',
isPopular: false,
isNew: false);
class Library {
final List<Book> allBooks = [];
final List<Author> allAuthors = [];
void addBook({
required String title,
required String authorName,
required bool isPopular,
required bool isNew,
}) {
var author = allAuthors.firstWhere(
(author) => author.name == authorName,
orElse: () {
final value = Author(allAuthors.length, authorName);
allAuthors.add(value);
return value;
},
);
var book = Book(allBooks.length, title, isPopular, isNew, author);
author.books.add(book);
allBooks.add(book);
}
Book getBook(String id) {
return allBooks[int.parse(id)];
}
List<Book> get popularBooks => [
...allBooks.where((book) => book.isPopular),
];
List<Book> get newBooks => [
...allBooks.where((book) => book.isNew),
];
}
| samples/navigation_and_routing/lib/src/data/library.dart/0 | {
"file_path": "samples/navigation_and_routing/lib/src/data/library.dart",
"repo_id": "samples",
"token_count": 655
} | 1,412 |
include: package:analysis_defaults/flutter.yaml
| samples/place_tracker/analysis_options.yaml/0 | {
"file_path": "samples/place_tracker/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,413 |
{
"images" : [
{
"filename" : "eat_new_orleans.jpg",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
| samples/platform_channels/ios/Runner/Assets.xcassets/eat_new_orleans.imageset/Contents.json/0 | {
"file_path": "samples/platform_channels/ios/Runner/Assets.xcassets/eat_new_orleans.imageset/Contents.json",
"repo_id": "samples",
"token_count": 179
} | 1,414 |
// Copyright 2020 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 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:platform_channels/src/image_basic_message_channel.dart';
/// Demonstrates how to use [BasicMessageChannel] to get an image from platform.
///
/// The widget uses [Image.memory] to display the image obtained from the
/// platform.
class PlatformImageDemo extends StatefulWidget {
const PlatformImageDemo({super.key});
@override
State<PlatformImageDemo> createState() => _PlatformImageDemoState();
}
class _PlatformImageDemoState extends State<PlatformImageDemo> {
Future<Uint8List>? imageData;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Platform Image Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Flexible(
child: FractionallySizedBox(
widthFactor: 1,
heightFactor: 0.6,
child: FutureBuilder<Uint8List>(
future: imageData,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.none) {
return const Placeholder();
} else if (snapshot.hasError) {
return Center(
child: Text(
(snapshot.error as PlatformException).message!,
),
);
} else if (snapshot.connectionState ==
ConnectionState.done) {
return Image.memory(
snapshot.data!,
fit: BoxFit.fill,
);
}
return const CircularProgressIndicator();
},
),
),
),
const SizedBox(
height: 16,
),
FilledButton(
onPressed: imageData != null
? null
: () {
setState(() {
imageData = PlatformImageFetcher.getImage();
});
},
child: const Text('Get Image'),
)
],
),
),
);
}
}
| samples/platform_channels/lib/src/platform_image_demo.dart/0 | {
"file_path": "samples/platform_channels/lib/src/platform_image_demo.dart",
"repo_id": "samples",
"token_count": 1311
} | 1,415 |
# Run with tooling from https://github.com/flutter/codelabs/tree/main/tooling/codelab_rebuild
name: Platform Design rebuild script
steps:
- name: Remove runner
rmdirs:
- android
- ios
- web
- name: Flutter recreate runner
flutter: create --platform android,ios,web --org dev.flutter .
- name: Patch web/manifest.json
path: web/manifest.json
patch-u: |
--- b/platform_design/web/manifest.json
+++ a/platform_design/web/manifest.json
@@ -5,7 +5,7 @@
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
- "description": "A new Flutter project.",
+ "description": "A project showcasing a Flutter app following different platform IA conventions.",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
- name: Update dependencies
flutter: pub upgrade --major-versions
- name: Build for iOS
platforms: [ macos ]
flutter: build ios --simulator
| samples/platform_design/codelab_rebuild.yaml/0 | {
"file_path": "samples/platform_design/codelab_rebuild.yaml",
"repo_id": "samples",
"token_count": 420
} | 1,416 |
name: platform_design
description: A project showcasing a Flutter app following different platform IA conventions.
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
english_words: ^4.0.0
flutter_lorem: ^2.0.0
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| samples/platform_design/pubspec.yaml/0 | {
"file_path": "samples/platform_design/pubspec.yaml",
"repo_id": "samples",
"token_count": 162
} | 1,417 |
#include "Generated.xcconfig"
| samples/platform_view_swift/ios/Flutter/Release.xcconfig/0 | {
"file_path": "samples/platform_view_swift/ios/Flutter/Release.xcconfig",
"repo_id": "samples",
"token_count": 12
} | 1,418 |
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina6_1" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14490.49"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="PlatformViewController" customModule="Runner" customModuleProvider="target">
<connections>
<outlet property="incrementLabel" destination="Fwz-pb-Vxw" id="LtN-bK-cIm"/>
<outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Button tapped 0 times." textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Fwz-pb-Vxw">
<rect key="frame" x="114.5" y="379.5" width="185" height="21.5"/>
<fontDescription key="fontDescription" type="system" pointSize="18"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="0Q4-1m-vDk">
<rect key="frame" x="144" y="433" width="126" height="30"/>
<fontDescription key="fontDescription" type="system" pointSize="15"/>
<state key="normal" title="Increment counter"/>
<connections>
<action selector="handleIncrement:" destination="-1" eventType="touchUpInside" id="6jY-7M-lj4"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="1Vb-F2-qFl">
<rect key="frame" x="125" y="495" width="164" height="30"/>
<fontDescription key="fontDescription" type="system" pointSize="15"/>
<state key="normal" title="Continue in Flutter View"/>
<connections>
<action selector="switchToFlutterView:" destination="-1" eventType="touchUpInside" id="tzA-cQ-gl6"/>
</connections>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="iOS" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="QgT-DT-gSd">
<rect key="frame" x="16" y="828" width="47" height="36"/>
<fontDescription key="fontDescription" type="system" pointSize="30"/>
<color key="textColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstItem="1Vb-F2-qFl" firstAttribute="top" secondItem="0Q4-1m-vDk" secondAttribute="bottom" constant="32" id="2Fr-G0-fL1"/>
<constraint firstItem="0Q4-1m-vDk" firstAttribute="centerX" secondItem="i5M-Pr-FkT" secondAttribute="centerX" id="6R3-W6-Dle"/>
<constraint firstItem="1Vb-F2-qFl" firstAttribute="centerX" secondItem="i5M-Pr-FkT" secondAttribute="centerX" id="8sv-fF-vKQ"/>
<constraint firstItem="QgT-DT-gSd" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" constant="16" id="8yF-bR-Te3"/>
<constraint firstItem="0Q4-1m-vDk" firstAttribute="top" secondItem="Fwz-pb-Vxw" secondAttribute="bottom" constant="32" id="QNR-n2-WAr"/>
<constraint firstItem="0Q4-1m-vDk" firstAttribute="centerY" secondItem="i5M-Pr-FkT" secondAttribute="centerY" id="YWH-R0-Md3"/>
<constraint firstItem="QgT-DT-gSd" firstAttribute="bottom" secondItem="i5M-Pr-FkT" secondAttribute="bottom" constant="-32" id="bIY-Nb-J3I"/>
<constraint firstItem="Fwz-pb-Vxw" firstAttribute="centerX" secondItem="i5M-Pr-FkT" secondAttribute="centerX" id="jcd-no-9jg"/>
</constraints>
<point key="canvasLocation" x="144.92753623188406" y="64.955357142857139"/>
</view>
</objects>
</document>
| samples/platform_view_swift/ios/Runner/PlatformViewController.xib/0 | {
"file_path": "samples/platform_view_swift/ios/Runner/PlatformViewController.xib",
"repo_id": "samples",
"token_count": 2516
} | 1,419 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/simple_shader/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/simple_shader/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,420 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>Simplistic Calculator</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>simplistic_calculator</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
</dict>
</plist>
| samples/simplistic_calculator/ios/Runner/Info.plist/0 | {
"file_path": "samples/simplistic_calculator/ios/Runner/Info.plist",
"repo_id": "samples",
"token_count": 674
} | 1,421 |
// Copyright 2020 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 'package:flutter/material.dart';
/// The [Favorites] class holds a list of favorite items saved by the user.
class Favorites extends ChangeNotifier {
final List<int> _favoriteItems = [];
List<int> get items => _favoriteItems;
void add(int itemNo) {
_favoriteItems.add(itemNo);
notifyListeners();
}
void remove(int itemNo) {
_favoriteItems.remove(itemNo);
notifyListeners();
}
}
| samples/testing_app/lib/models/favorites.dart/0 | {
"file_path": "samples/testing_app/lib/models/favorites.dart",
"repo_id": "samples",
"token_count": 180
} | 1,422 |
include: package:analysis_defaults/flutter.yaml
| samples/veggieseasons/analysis_options.yaml/0 | {
"file_path": "samples/veggieseasons/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,423 |
// Copyright 2018 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 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:veggieseasons/data/app_state.dart';
import 'package:veggieseasons/data/preferences.dart';
import 'package:veggieseasons/data/veggie.dart';
import 'package:veggieseasons/styles.dart';
import 'package:veggieseasons/widgets/veggie_card.dart';
class ListScreen extends StatelessWidget {
const ListScreen({this.restorationId, super.key});
final String? restorationId;
Widget _generateVeggieRow(Veggie veggie, Preferences prefs,
{bool inSeason = true}) {
return Padding(
padding: const EdgeInsets.only(left: 16, right: 16, bottom: 24),
child: FutureBuilder<Set<VeggieCategory>>(
future: prefs.preferredCategories,
builder: (context, snapshot) {
final data = snapshot.data ?? <VeggieCategory>{};
return VeggieCard(veggie, inSeason, data.contains(veggie.category));
}),
);
}
@override
Widget build(BuildContext context) {
return CupertinoTabView(
restorationScopeId: restorationId,
builder: (context) {
var dateString = DateFormat('MMMM y').format(DateTime.now());
final appState = Provider.of<AppState>(context);
final prefs = Provider.of<Preferences>(context);
final themeData = CupertinoTheme.of(context);
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarBrightness: MediaQuery.platformBrightnessOf(context)),
child: SafeArea(
bottom: false,
child: ListView.builder(
restorationId: 'list',
itemCount: appState.allVeggies.length + 2,
itemBuilder: (context, index) {
if (index == 0) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 24, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(dateString.toUpperCase(),
style: Styles.minorText(themeData)),
Text('In season today',
style: Styles.headlineText(themeData)),
],
),
);
} else if (index <= appState.availableVeggies.length) {
return _generateVeggieRow(
appState.availableVeggies[index - 1],
prefs,
);
} else if (index <= appState.availableVeggies.length + 1) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 24, 16, 16),
child: Text('Not in season',
style: Styles.headlineText(themeData)),
);
} else {
var relativeIndex =
index - (appState.availableVeggies.length + 2);
return _generateVeggieRow(
appState.unavailableVeggies[relativeIndex], prefs,
inSeason: false);
}
},
),
),
);
},
);
}
}
| samples/veggieseasons/lib/screens/list.dart/0 | {
"file_path": "samples/veggieseasons/lib/screens/list.dart",
"repo_id": "samples",
"token_count": 1691
} | 1,424 |
// 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:js_interop';
@JS()
@staticInterop
external FlutterWebStartupAnalyzer get flutterWebStartupAnalyzer;
@JS()
@staticInterop
class FlutterWebStartupAnalyzer {
external factory FlutterWebStartupAnalyzer();
}
extension FlutterWebStartupAnalyzerExtensions on FlutterWebStartupAnalyzer {
external JSObject get timings;
external void markStart(String name);
external void markFinished(String name);
external void capture(String name);
external void captureAll();
external void capturePaint();
external void report();
}
| samples/web/_packages/web_startup_analyzer/lib/src/startup_analyzer.dart/0 | {
"file_path": "samples/web/_packages/web_startup_analyzer/lib/src/startup_analyzer.dart",
"repo_id": "samples",
"token_count": 199
} | 1,425 |
samples:
- name: Material 3
author: Flutter
screenshots:
- url: images/material_3_components.png
alt: Components tab of the Material 3 demo
- url: images/material_3_color.png
alt: Colors tab of the Material 3 demo
- url: images/material_3_typography.png
alt: Typography tab of the Material 3 demo
- url: images/material_3_elevation.png
alt: Elevation tab of the Material 3 demo
- url: images/material_3_green.png
alt: Elevation tab of the Material 3 demo with seed color of green
source: https://github.com/flutter/samples/tree/main/material_3_demo
description: >
Showcases Material 3 features in the Flutter Material library.
These features include updated components, typography, color system and elevation support.
difficulty: beginner
widgets:
- Theme
- TextButton
- ElevatedButton
- OutlinedButton
- Text
- Card
- AppBar
packages: [ ]
tags: [ "material", "design", "gallery" ]
platforms: [ "ios", "android", "web", "windows", "macos", "linux" ]
type: demo
web: web/material_3_demo
- name: Rich Text Editor
author: Flutter
screenshots:
- url: images/simple_editor_active.png
alt: Advanced text editing with activity
- url: images/simple_editor_initial.png
alt: Advanced text editing in initial state
source: https://github.com/flutter/samples/tree/main/simplistic_editor
description: >
This is a fancy text editor sample which shows how to consume fine-grain
text editing and selection details from the framework's TextEditingDeltas
APIs.
difficulty: advanced
widgets:
- TextInput
packages: []
tags: ["demo", "text"]
platforms: ["ios", "android", "web", "windows", "macos", "linux"]
type: demo
web: web/simplistic_editor
- name: Gallery
author: Flutter
screenshots:
- url: images/gallery1.png
alt: Gallery app screenshot
- url: images/gallery2.png
alt: Rally app screenshot
- url: images/gallery3.png
alt: Fortnightly app screenshot
- url: images/gallery4.png
alt: Crane app screenshot
- url: images/gallery5.png
alt: Shrine app screenshot
source: https://github.com/flutter/gallery
web: https://flutter-gallery-archive.web.app
description: >
A collection of Material Design & Cupertino widgets, behaviors,
and vignettes implemented with Flutter.
difficulty: intermediate
widgets:
- AlertDialog
- AppBar
- BottomAppBar
- BottomNavigationBar
- BottomSheet
- Card
- Checkbox
- ChoiceChip
- CircularProgressIndicator
- Container
- CupertinoActivityIndicator
- CupertinoAlertDialog
- CupertinoButton
- CupertinoButton
- CupertinoDatePicker
- CupertinoDialogAction
- CupertinoNavigationBar
- CupertinoPageScaffold
- CupertinoSegmentedControl
- CupertinoSlider
- CupertinoSlidingSegmentedControl
- CupertinoSliverRefreshControl
- CupertinoSwitch
- CupertinoTabView
- CupertinoTextField
- CupertinoTheme
- DayPicker
- FilterChip
- FlatButton
- FloatingActionButton
- GridTile
- GridView
- Icon
- InputChip
- LayoutBuilder
- LinearProgressIndicator
- ListTile
- ListView
- MaterialBanner
- MonthPicker
- PaginatedDataTable
- PopupMenuButton
- PopupMenuItem
- Radio
- RaisedButton
- RangeSlider
- Scaffold
- SimpleDialog
- Slider
- SnackBar
- Switch
- TabBar
- TabBarView
- TextField
- TextFormField
- Tooltip
- YearPicker
packages:
- flutter/material
- flutter/cupertino
- google_fonts
- scoped_model
tags: ['intermediate', 'sample', 'gallery', 'material', 'design', 'vignettes']
platforms: ['web', 'ios', 'android']
type: demo
- name: Web Embedding
author: Flutter and Angular
screenshots:
- url: images/web_embedding1.png
alt: A Flutter app embedded in an Angular app
- url: images/web_embedding2.png
alt: A Flutter app embedded in an Angular app
source: https://github.com/flutter/samples/tree/main/web_embedding
description: >
An example app showing how to embed Flutter in a web application using Angular
difficulty: advanced
widgets: []
packages: []
platforms: ['web']
tags: ['demo', 'web', 'add-to-app', 'embedding']
web: https://flutter-angular.web.app/
type: demo
- name: Add to App
author: Flutter
screenshots:
- url: images/add_to_app1.png
alt: Add_to_app screenshot
- url: images/add_to_app2.png
alt: Add_to_app screenshot
source: https://github.com/flutter/samples/tree/main/add_to_app
description: >
Android and iOS projects that each import a standalone Flutter module.
difficulty: advanced
widgets:
- WidgetsFlutterBinding
- MethodChannel
packages:
- flutter/material
- flutter/services
- provider
tags: ['advanced', 'sample', 'add-to-app', 'android', 'ios', 'native', 'embedding']
platforms: ['ios', 'android']
type: sample
- name: Code Sharing
author: Flutter
screenshots:
- url: images/code_sharing.jpg
alt: Counter app communicating with server
source: https://github.com/flutter/samples/tree/main/code_sharing
description: >
Demonstrates simple way to share business logic between a Flutter app and
a server running Dart.
difficulty: intermediate
packages:
- freezed
- shelf
tags: ['intermediate', 'sample', 'code-sharing', 'dart', 'server']
platforms: ['android', 'ios', 'linux', 'macos', 'web', 'windows']
type: sample
- name: Animations
author: Flutter
screenshots:
- url: images/animations1.png
alt: Animations sample screenshot
- url: images/animations2.png
alt: Animations sample screenshot
- url: images/animations3.png
alt: Animations sample screenshot
source: https://github.com/flutter/samples/tree/main/animations
description: >
Sample apps that showcasing Flutter's animation features.
difficulty: advanced
widgets:
- AnimatedContainer
- PageRouteBuilder
- AnimationController
- SingleTickerProviderStateMixin
- Tween
- AnimatedBuilder
- TweenSequence
- TweenSequenceItem
packages:
- flutter/material
tags: ['intermediate', 'sample', 'animation']
platforms: ['ios', 'android', 'web']
type: sample
web: web/animations
- name: Flutter Maps Firestore
author: Flutter
screenshots:
- url: images/flutter_maps_firestore1.png
alt: Flutter maps firestore screenshot
- url: images/flutter_maps_firestore2.png
alt: Flutter maps firestore screenshot
source: https://github.com/flutter/samples/tree/main/flutter_maps_firestore
description: >
A Flutter sample app that shows the end product of the Cloud Next '19 talk
Build Mobile Apps With Flutter and Google Maps.
difficulty: advanced
widgets:
- GoogleMap
packages:
- flutter/material
- cloud_firestore
- google_maps_flutter
- google_maps_webservice
tags: ['intermediate', 'sample', 'firebase', 'maps']
platforms: ['ios', 'android']
type: sample
- name: Isolate Example
author: Flutter
screenshots:
- url: images/isolate1.png
alt: Isolate example screenshot
- url: images/isolate2.png
alt: Isolate example screenshot
- url: images/isolate3.png
alt: Isolate example screenshot
source: https://github.com/flutter/samples/tree/main/isolate_example
description: >
A sample application that demonstrate best practices when using
isolates.
difficulty: intermediate
widgets:
- FutureBuilder
- AnimationController
packages:
- dart:isolate
- dart:math
tags: ['intermediate', 'sample', 'isolates', 'concurrency']
platforms: ['ios', 'android']
type: sample
- name: Place Tracker
author: Flutter
screenshots:
- url: images/place_tracker1.png
alt: Place Tracker screenshot
- url: images/place_tracker2.png
alt: Place Tracker screenshot
- url: images/place_tracker3.png
alt: Place Tracker screenshot
- url: images/place_tracker4.png
alt: Place Tracker screenshot
source: https://github.com/flutter/samples/tree/main/place_tracker
description: >
A sample place tracking app that uses the google_maps_flutter plugin. Keep
track of your favorite places, places you've visited, and places you want
to go. View details about these places, show them on a map, and get
directions to them.
difficulty: intermediate
widgets:
- GoogleMap
packages:
- google_maps_flutter
tags: ['intermediate', 'sample', 'json', 'serialization']
platforms: ['android']
type: sample
- name: Platform Design
author: Flutter
screenshots:
- url: images/platform_design1.png
alt: Platform Design screenshot
- url: images/platform_design2.png
alt: Platform Design screenshot
- url: images/platform_design3.png
alt: Platform Design screenshot
- url: images/platform_design4.png
alt: Platform Design screenshot
- url: images/platform_design5.png
alt: Platform Design screenshot
- url: images/platform_design6.png
alt: Platform Design screenshot
- url: images/platform_design7.png
alt: Platform Design screenshot
source: https://github.com/flutter/samples/tree/main/platform_design
description: >
A Flutter app that maximizes application code reuse while adhering to
different design patterns on Android and iOS
difficulty: advanced
widgets:
- TargetPlatform
packages:
- flutter/material
- flutter/cupertino
tags: ['advanced', 'sample', 'ios']
platforms: ['ios', 'android']
type: sample
- name: Platform View Swift
author: Flutter
screenshots:
- url: images/platform_view_swift1.png
alt: Platform View Swift screenshot
- url: images/platform_view_swift2.png
alt: Platform View Swift screenshot
source: https://github.com/flutter/samples/tree/main/platform_view_swift
description: >
A Flutter sample app that combines a native iOS UIViewController with a
full-screen Flutter view.
difficulty: intermediate
widgets:
- MethodChannel
packages:
- flutter/material
- flutter/services
tags: ['advanced', 'sample', 'ios']
platforms: ['ios']
type: sample
- name: Infinite List
author: Flutter
screenshots:
- url: images/infinite_list.png
alt: Infinite List screenshot
source: https://github.com/flutter/samples/tree/main/infinite_list
description: >
A Flutter sample app that shows an implementation of the "infinite list" UX pattern.
That is, a list is shown to the user as if it was continuous although it is internally
paginated. This is a common feature of mobile apps, from shopping catalogs
through search engines to social media clients.
difficulty: intermediate
widgets:
- Selector
- AppBar
- ListTile
- ListView
packages:
- provider
- meta
tags: ['sample', 'material', 'design', 'android', 'ios']
platforms: ['ios', 'android']
type: sample
- name: IOS App Clip
author: Flutter
screenshots:
- url: images/ios_app_clip.png
alt: IOS App Clip screenshot
source: https://github.com/flutter/samples/tree/main/ios_app_clip
description: >
A Flutter sample app that shows the demonstrating integration with iOS 14's App Clip,
the App Clip target is rendered by Flutter and uses a plugin.
difficulty: intermediate
widgets:
- CupertinoApp
- AppBar
- FlutterLogo
packages:
- device_info
tags: ['sample', 'Device Info', 'ios']
platforms: ['ios']
type: sample
- name: Testing App
author: Flutter
screenshots:
- url: images/testing_app1.png
alt: Testing App screenshot
- url: images/testing_app2.png
alt: Testing App screenshot
source: https://github.com/flutter/samples/tree/main/testing_app
description: >
A Flutter sample app that shows different types of testing in Flutter.
difficulty: intermediate
widgets:
- AppBar
- ListTile
- ListView
- Snackbar
packages:
- provider
tags: ['sample', 'material', 'android', 'ios']
platforms: ['ios', 'android']
type: sample
- name: Provider Shopper
author: Flutter
screenshots:
- url: images/provider_shopper1.png
alt: Provider Shopper screenshot
- url: images/provider_shopper2.png
alt: Provider Shopper screenshot
- url: images/provider_shopper3.png
alt: Provider Shopper screenshot
source: https://github.com/flutter/samples/tree/main/provider_shopper
description: >
A Flutter sample app that shows a state management approach using the Provider package.
difficulty: intermediate
widgets:
- Provider
- MultiProvider
- ChangeNotifier
packages:
- provider
tags: ['intermediate', 'sample', 'provider']
platforms: ['ios', 'android', 'web']
type: sample
web: web/provider_shopper
- name: Web Dashboard
author: Flutter
screenshots:
- url: images/web_dashboard1.png
alt: Web Dashboard screenshot
- url: images/web_dashboard2.png
alt: Web Dashboard screenshot
- url: images/web_dashboard3.png
alt: Web Dashboard screenshot
source: https://github.com/flutter/samples/tree/main/experimental/web_dashboard
description: >
A dashboard app that displays daily entries. Demonstrates AdaptiveScaffold and NavigationRail. Showcases how to
use Firebase, but uses a mock backend by default.
difficulty: advanced
widgets:
- AdaptiveScaffold
- NavigationRail
- FutureBuilder
- StreamBuilder
packages:
- firebase
tags: ['intermediate', 'sample', 'firebase']
platforms: ['ios', 'android', 'web']
type: sample
web: web/web_dashboard
- name: Form App
author: Flutter
screenshots:
- url: images/form_app1.png
alt: Form App screenshot
- url: images/form_app2.png
alt: Form App screenshot
- url: images/form_app3.png
alt: Form App screenshot
source: https://github.com/flutter/samples/tree/main/form_app
description: >
A Flutter sample app that shows how to use Forms.
difficulty: intermediate
widgets:
- Form
packages: []
tags: ['intermediate', 'sample', 'forms']
platforms: ['ios', 'android', 'web']
type: sample
web: web/form_app
- name: Navigation and Routing
author: Flutter
screenshots:
- url: images/navigation_and_routing1.png
alt: Navigation and Routing screenshot
- url: images/navigation_and_routing2.png
alt: Navigation and Routing screenshot
- url: images/navigation_and_routing3.png
alt: Navigation and Routing screenshot
- url: images/navigation_and_routing4.png
alt: Navigation and Routing screenshot
source: https://github.com/flutter/samples/tree/main/navigation_and_routing
description: >
A Flutter sample app that shows how to use how to use the Router API to
handle common navigation scenarios.
difficulty: advanced
widgets:
- Router
packages: []
tags: ['advanced', 'sample', 'navigation', 'router']
platforms: ['ios', 'android', 'web']
type: sample
web: web/navigation_and_routing
- name: Photo Search app
author: Flutter
screenshots:
- url: images/desktop_photo_search-fluent_ui.png
alt: Desktop Photo Search with FluentUI widgets
- url: images/desktop_photo_search-material.png
alt: Desktop Photo Search with Material widgets
source: https://github.com/flutter/samples/tree/main/desktop_photo_search
description: >
This is the Photo Search app, built out with two different widget sets,
`material` shows the Photo Search app built with Material widgets, and
`fluent_ui` shows the Photo Search app built with Fluent UI widgets.
difficulty: medium
widgets: []
packages:
- built_collection
- built_value
- file_selector
- fluent_ui
- flutter/material
- provider
- url_launcher
tags: ['desktop', 'rest-api']
platforms: ['windows', 'macos', 'linux']
type: sample
- name: Slide Puzzle
author: Very Good Ventures
screenshots:
- url: images/slide_puzzle1.png
alt: Slide Puzzle screenshot
source: https://github.com/VGVentures/slide_puzzle
description: >
A slide puzzle built for Flutter Challenge.
difficulty: advanced
widgets: []
packages: []
platforms: ['web']
tags: ['demo', 'game']
type: demo
- name: Game Template
author: Flutter
screenshots:
- url: images/loading_screen.png
alt: Loading screen
- url: images/level_selector.png
alt: Level selection screen
source: https://github.com/flutter/samples/tree/main/game_template
description: >
This is a game template that shows how to build much of the dressing
around an actual game. The game itself is very simple - the value in this
sample is everything around the game.
difficulty: beginner
widgets:
- GoRouter
- AppLifecycleObserver
packages:
- audioplayers
- firebase_crashlytics
- games_services
- go_router
- google_mobile_ads
- in_app_purchase
- logging
- provider
- shared_preferences
tags: ["games", "firebase", "ads", "crashlytics", "routing"]
platforms: ["ios", "android", "web", "windows", "macos", "linux"]
type: demo
web: web/game_template
- name: Dice
author: Jaime Blasco
screenshots:
- url: images/dice.png
alt: Dice screenshot
source: https://github.com/jamesblasco/zflutter/blob/master/zflutter/example/lib/examples/dice/dice.dart
description: >
A demo of 3d animation using dice
difficulty: advanced
widgets: []
packages: []
platforms: ['web']
tags: ['demo', 'animation']
web: https://z.flutter.gallery/#/dice
type: demo
| samples/web/samples_index/lib/src/samples.yaml/0 | {
"file_path": "samples/web/samples_index/lib/src/samples.yaml",
"repo_id": "samples",
"token_count": 7131
} | 1,426 |
{
"name": "ng-flutter",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"prebuild": "pushd flutter && flutter clean && flutter build web && popd",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^17.1.0",
"@angular/cdk": "^17.1.0",
"@angular/common": "^17.1.0",
"@angular/compiler": "^17.1.0",
"@angular/core": "^17.1.0",
"@angular/forms": "^17.1.0",
"@angular/material": "^17.1.0",
"@angular/platform-browser": "^17.1.0",
"@angular/platform-browser-dynamic": "^17.1.0",
"@angular/router": "^17.1.0",
"rxjs": "~7.8.1",
"tslib": "^2.6.2",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.1.1",
"@angular/cli": "~17.1.1",
"@angular/compiler-cli": "^17.1.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.1",
"karma": "~6.4.2",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.3.3"
},
"sideEffects": false
}
| samples/web_embedding/ng-flutter/package.json/0 | {
"file_path": "samples/web_embedding/ng-flutter/package.json",
"repo_id": "samples",
"token_count": 599
} | 1,427 |
title: Flutter
url: https://docs.flutter.dev
main-url: https://flutter.dev
email: [email protected]
google_analytics_id: UA-67589403-1
google_site_verification: HFqxhSbf9YA_0rBglNLzDiWnrHiK_w4cqDh2YD2GEY4
google_tag_manager_id: GTM-ND4LWWZ
default_share_image: /assets/images/flutter-logo-sharing.png
github_username: flutter
branch: main
repo:
organization: https://github.com/flutter
this: https://github.com/flutter/website
flutter: https://github.com/flutter/flutter
samples: https://github.com/flutter/samples
packages: https://github.com/flutter/packages
gallery-archive: https://github.com/flutter/gallery
engine: https://github.com/flutter/engine
uxr: https://github.com/flutter/uxr
wonderous: https://github.com/gskinnerTeam/flutter-wonderous-app
dart:
api: https://api.dart.dev
sdk:
channel: stable
sdk:
channel: stable # When changing this value also update it in src/_assets/js/archive.js
social:
twitter: https://twitter.com/FlutterDev
youtube: https://www.youtube.com/@flutterdev
dart-site: https://dart.dev
news: https://news.dartlang.org
api: https://api.flutter.dev
main-api: https://main-api.flutter.dev
pub: https://pub.dev
pub-api: https://pub.dev/documentation
pub-pkg: https://pub.dev/packages
flutter-medium: https://medium.com/flutter
medium: https://medium.com
dartpad: https://dartpad.dev
gallery-archive: https://flutter-gallery-archive.web.app
material: https://m3.material.io
material2: https://m2.material.io
so: https://stackoverflow.com
github: https://github.com
flutter-assets: https://flutter.github.io/assets-for-api-docs/assets
android-dev: https://developer.android.com
apple-dev: https://developer.apple.com
google-blog: https://developers.googleblog.com
developers: https://developers.google.com
codelabs: https://codelabs.developers.google.com
groups: https://groups.google.com
firebase: https://firebase.google.com
wonderous: https://wonderous.app/
youtube-site: https://youtube.com
yt:
set: 'frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen loading="lazy"'
set-short: 'frameborder="0" allowfullscreen loading="lazy"'
watch: 'https://www.youtube.com/watch'
embed: 'https://www.youtube.com/embed'
playlist: 'https://www.youtube.com/playlist?list='
## Software minimum versions
appmin:
git_win: 2.27
git_mac: 2.27
vscode: 1.77
android_studio: '2023.1 (Hedgehog)'
intellij_idea: '2023.1'
android_sdk: 21
powershell: 5.0
xcode: '14'
ios: '17'
cocoapods: '1.10'
devmin:
windows: '64-bit version of Microsoft Windows 10'
macos: '10.15 (Catalina)'
linux:
debian: 11
ubuntu: '20.04 LTS'
targetmin:
windows: 'Microsoft Windows 7'
macos: '10.14 (Ventura)'
linux:
debian: 10
ubuntu: '18.04 LTS'
ios: 12
android: 'Android API level 21'
## Software current versions
appnow:
flutter: '3.19.3'
vscode: '1.86'
android_studio: '2023.1 (Hedgehog) or later'
android_sdk: '34.0.0'
intellij: '2023.3'
powershell: 5.1
xcode: '15'
ios: '17'
cocoapods: '1.13'
########### Jekyll ###########
source: src
strict_front_matter: true
permalink: pretty
exclude: []
liquid:
error_mode: strict
strict_filters: true
sass:
sass_dir: _sass
cache: false
style: compressed
load_paths:
- ../node_modules
plugins:
- jekyll-toc
toc:
min_level: 2
max_level: 3
defaults:
- scope:
path: assets/images
values:
image: true
- scope:
path: assets/js
values:
js: true
- scope:
path: ''
values:
layout: default
show-nav-get-started-button: true
show_banner: true
show_footer: true
- scope:
path: ''
values:
toc: true
- scope:
path: 'accessibility-and-localization'
values:
show_breadcrumbs: true
- scope:
path: 'add-to-app'
values:
show_breadcrumbs: true
- scope:
path: 'cookbook'
values:
show_breadcrumbs: true
- scope:
path: 'data-and-backend'
values:
show_breadcrumbs: true
- scope:
path: 'deployment'
values:
show_breadcrumbs: true
- scope:
path: 'get-started'
values:
show_breadcrumbs: true
- scope:
path: 'get-started/flutter-for'
values:
show_breadcrumbs: false
- scope:
path: 'packages-and-plugins'
values:
show_breadcrumbs: true
- scope:
path: 'perf'
values:
show_breadcrumbs: true
- scope:
path: 'platform-integration'
values:
show_breadcrumbs: true
- scope:
path: 'release'
values:
show_breadcrumbs: true
- scope:
path: 'testing'
values:
show_breadcrumbs: true
- scope:
path: 'tools'
values:
show_breadcrumbs: true
- scope:
path: 'ui'
values:
show_breadcrumbs: true
- scope:
path: 'ui/widgets'
values:
toc: false
########### Alerts ###########
# TODO these are bootstrap related, will not be supported
alert:
bonus: >-
<aside class="alert alert-info" role="alert" markdown="1">
**Bonus questions!**
important: >-
<aside class="alert alert-warning alert-icon" role="alert" markdown="1">
<i class="material-symbols" aria-hidden="true">error</i> **Important**
info: >-
<aside class="alert alert-info" role="alert" markdown="1">
<i class="material-symbols" aria-hidden="true">info</i>
note: >-
<aside class="alert alert-info" role="alert" markdown="1">
<i class="material-symbols" aria-hidden="true">info</i> **Note**
version-note: >-
<aside class="alert alert-info" role="alert" markdown="1">
<i class="material-symbols" aria-hidden="true">merge_type</i> **Version note**
recommend: >-
<aside class="alert alert-success alert-icon" role="alert" markdown="1">
<i class="material-symbols" aria-hidden="true">bolt</i>
secondary: >-
<aside class="alert alert-secondary" role="alert" markdown="1">
tip: >-
<aside class="alert alert-success" role="alert" markdown="1">
<i class="material-symbols" aria-hidden="true">lightbulb</i> **Tip**
warning: >-
<aside class="alert alert-warning" role="alert" markdown="1">
<i class="material-symbols" aria-hidden="true">warning</i> **Warning**
end: </aside>
########### Custom ###########
custom:
dartpad:
embed-dart-prefix: https://dartpad.dev/embed-dart.html
embed-flutter-prefix: https://dartpad.dev/embed-flutter.html
embed-html-prefix: https://dartpad.dev/embed-html.html
embed-inline-prefix: https://dartpad.dev/embed-inline.html
| website/_config.yml/0 | {
"file_path": "website/_config.yml",
"repo_id": "website",
"token_count": 2644
} | 1,428 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
viewBox="0 0 1920 1080"
version="1.1"
id="svg38"
sodipodi:docname="article-hero-image.svg"
width="1920"
height="1080"
inkscape:version="1.0 (4035a4f, 2020-05-01)"
inkscape:export-filename="article-hero-image.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96">
<metadata
id="metadata42">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
</cc:Work>
</rdf:RDF>
</metadata>
<sodipodi:namedview
pagecolor="#f5f5f5"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="1"
inkscape:pageshadow="2"
inkscape:window-width="1280"
inkscape:window-height="719"
id="namedview40"
showgrid="false"
inkscape:zoom="0.59"
inkscape:cx="1135.7043"
inkscape:cy="379.80129"
inkscape:window-x="0"
inkscape:window-y="23"
inkscape:window-maximized="0"
inkscape:current-layer="svg38"
inkscape:document-rotation="0" />
<defs
id="defs16">
<marker
id="arrow-container-1"
orient="auto-start-reverse"
viewBox="0 0 1 1"
markerWidth="3"
markerHeight="3"
refX="0.5"
refY="0.5">
<path
d="M 1,0.5 0.5,0 v 1 z"
id="path2"
inkscape:connector-curvature="0"
style="fill:#f50057" />
</marker>
<marker
id="arrow-container-2"
orient="auto-start-reverse"
viewBox="0 0 1 1"
markerWidth="3"
markerHeight="3"
refX="0.5"
refY="0.5">
<path
d="M 1,0.5 0.5,0 v 1 z"
id="path5"
inkscape:connector-curvature="0"
style="fill:#000000" />
</marker>
<filter
id="shadow-container"
x="-0.5"
y="-0.5"
width="2"
height="2">
<feGaussianBlur
stdDeviation="4"
id="feGaussianBlur8" />
</filter>
<linearGradient
id="gradient-container"
x1="10.45825"
y1="39.442543"
x2="35.558052"
y2="83.367195"
gradientTransform="matrix(10.370296,0,0,7.2592072,932.5437,-14.818481)"
gradientUnits="userSpaceOnUse">
<stop
offset="55%"
stop-color="#ffffff"
id="stop11" />
<stop
offset="100%"
stop-color="#fdccdd"
id="stop13" />
</linearGradient>
</defs>
<g
id="g870"
transform="translate(-35.59322,98.305085)">
<rect
transform="rotate(-45)"
y="251.06944"
x="-511.28705"
height="306.9281"
width="959.15027"
id="rect21"
style="display:inline;opacity:1;fill:#1574bc;fill-opacity:1;stroke:none;stroke-width:2.5309341;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:markers stroke fill" />
<rect
transform="rotate(45)"
y="250.91998"
x="-94.412918"
height="306.9281"
width="959.15027"
id="rect39"
style="display:inline;opacity:1;fill:#dae1e8;fill-opacity:1;stroke:none;stroke-width:6.90588188;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:markers stroke fill" />
<rect
transform="rotate(45)"
y="557.84802"
x="-94.412918"
height="306.9281"
width="959.15027"
id="rect39-5"
style="display:inline;opacity:1;fill:#1574bc;fill-opacity:1;stroke:none;stroke-width:6.90588188;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:markers stroke fill" />
<rect
transform="rotate(-45)"
y="-53.685795"
x="-252.50293"
height="306.9281"
width="959.15027"
id="rect21-0"
style="display:inline;opacity:1;fill:#55c4fa;fill-opacity:1;stroke:none;stroke-width:2.5309341;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;paint-order:markers stroke fill" />
</g>
<path
inkscape:connector-curvature="0"
id="path913"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:360px;line-height:125%;font-family:'Product Sans';-inkscape-font-specification:'Product Sans Bold';letter-spacing:0px;word-spacing:0px;fill:#addaf2;fill-opacity:1;stroke:none;stroke-width:1.62564px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 544.1437,627.46613 -29.84678,45.64802 c 8.97354,3.12123 16.38647,8.77847 22.23878,16.9717 5.85231,7.80308 8.77846,17.36185 8.77846,28.67631 0,14.04555 -4.87692,26.14032 -14.63077,36.28433 -9.75385,9.75385 -21.65355,14.63077 -35.6991,14.63077 -14.04554,0 -26.14031,-4.87692 -36.28432,-14.63077 -9.75385,-10.14401 -14.63077,-22.23878 -14.63077,-36.28433 0,-7.41292 1.17046,-14.04554 3.51138,-19.89785 2.73108,-5.85231 6.43755,-12.09477 11.11939,-18.72739 l 50.9151,-75.4948 z m 82.16558,0 -29.84678,45.64802 c 8.97354,3.12123 16.38647,8.77847 22.23878,16.9717 5.85231,7.80308 8.77846,17.36185 8.77846,28.67631 0,14.04555 -4.87692,26.14032 -14.63077,36.28433 -9.75385,9.75385 -21.65355,14.63077 -35.69909,14.63077 -14.04554,0 -26.14031,-4.87692 -36.28432,-14.63077 -9.75385,-10.14401 -14.63077,-22.23878 -14.63077,-36.28433 0,-7.41292 1.17046,-14.04554 3.51138,-19.89785 2.73108,-5.85231 6.43754,-12.09477 11.11939,-18.72739 l 50.91509,-75.4948 z"
sodipodi:nodetypes="cccscscscccccccscscscccc" />
<path
inkscape:connector-curvature="0"
id="path917"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:360px;line-height:125%;font-family:'Product Sans';-inkscape-font-specification:'Product Sans Bold';letter-spacing:0px;word-spacing:0px;fill:#addaf2;fill-opacity:1;stroke:none;stroke-width:1.62564px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 1604.9939,1026.8929 29.8468,-45.6479 c -8.5834,-3.12128 -15.9963,-8.58344 -22.2388,-16.38652 -5.8523,-8.19323 -8.7785,-17.94708 -8.7785,-29.26155 0,-14.04555 4.8769,-25.94524 14.6308,-35.69909 10.144,-10.14401 22.2388,-15.21601 36.2843,-15.21601 14.0455,0 25.9452,5.072 35.6991,15.21601 9.7539,9.75385 14.6308,21.65354 14.6308,35.69909 0,7.41293 -1.3655,14.04554 -4.0966,19.89785 -2.3409,5.85231 -5.8523,12.09478 -10.5342,18.72739 l -50.9151,75.49473 z m 84.1656,0 29.8467,-45.6479 c -8.5833,-3.12128 -15.9962,-8.58344 -22.2387,-16.38652 -5.8523,-8.19323 -8.7785,-17.94708 -8.7785,-29.26155 0,-14.04555 4.8769,-25.94524 14.6308,-35.69909 10.144,-10.14401 22.2388,-15.21601 36.2843,-15.21601 14.0455,0 25.9452,5.072 35.6991,15.21601 9.7539,9.75385 14.6308,21.65354 14.6308,35.69909 0,7.41293 -1.3656,14.04554 -4.0967,19.89785 -2.3409,5.85231 -5.8522,12.09478 -10.5341,18.72739 l -50.9151,75.49473 z"
sodipodi:nodetypes="cccscscscccccccscscscccc" />
<text
transform="scale(0.91886412,1.0883002)"
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:26.9484px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.673711px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
x="626.84277"
y="660.67554"
id="text887"><tspan
sodipodi:role="line"
id="tspan885"
x="626.84277"
y="660.67554"
style="font-style:normal;font-variant:normal;font-weight:500;font-stretch:normal;font-size:129.352px;line-height:100%;font-family:Roboto;-inkscape-font-specification:'Roboto Medium';stroke-width:0.673711px">Constraints go down.</tspan><tspan
sodipodi:role="line"
x="626.84277"
y="790.02753"
style="font-style:normal;font-variant:normal;font-weight:500;font-stretch:normal;font-size:129.352px;line-height:100%;font-family:Roboto;-inkscape-font-specification:'Roboto Medium';stroke-width:0.673711px"
id="tspan891">Sizes go up.</tspan><tspan
sodipodi:role="line"
x="626.84277"
y="919.37952"
style="font-style:normal;font-variant:normal;font-weight:500;font-stretch:normal;font-size:129.352px;line-height:100%;font-family:Roboto;-inkscape-font-specification:'Roboto Medium';stroke-width:0.673711px"
id="tspan889">Parent sets position.</tspan></text>
<g
inkscape:export-ydpi="96"
inkscape:export-xdpi="96"
inkscape:export-filename="./g4693.png"
id="g4693"
transform="translate(81.497053,-74.366694)">
<rect
transform="matrix(8.6764121,0,0,8.6764121,932.5437,-8517.7022)"
style="fill:#000000;filter:url(#shadow-container)"
id="rect20"
ry="10"
rx="10"
height="47.5"
width="70"
y="1005"
x="15" />
<rect
style="fill:url(#gradient-container);stroke:#3b75ad;stroke-width:43.3821"
id="rect22"
ry="86.764122"
rx="86.764122"
height="412.12958"
width="607.34882"
y="202.09183"
x="1062.6899" />
<rect
style="fill:#4dd0e1;stroke-width:8.67641"
id="rect24"
height="260.29236"
width="347.05649"
y="332.23801"
x="1192.8361" />
<line
style="stroke:#f50057;stroke-width:17.3528;marker-start:url(#arrow-container-1);marker-end:url(#arrow-container-1)"
id="line26"
y2="462.38419"
x2="1166.8069"
y1="462.38419"
x1="1106.0719" />
<line
style="stroke:#f50057;stroke-width:17.3528;marker-start:url(#arrow-container-1);marker-end:url(#arrow-container-1)"
id="line28"
y2="462.38419"
x2="1626.6567"
y1="462.38419"
x1="1565.9219" />
<line
style="stroke:#f50057;stroke-width:17.3528;marker-start:url(#arrow-container-1);marker-end:url(#arrow-container-1)"
id="line30"
y2="306.20877"
x2="1366.3644"
y1="245.47389"
x1="1366.3644" />
<line
style="stroke:#000000;stroke-width:17.353;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#arrow-container-2);marker-end:url(#arrow-container-2)"
id="line34"
y2="137.01874"
x2="1670.0388"
y1="137.01874"
x1="1071.3663" />
<line
style="stroke:#000000;stroke-width:17.3528;stroke-opacity:1;marker-start:url(#arrow-container-2);marker-end:url(#arrow-container-2)"
id="line36"
y2="609.88318"
x2="997.61676"
y1="210.76825"
x1="997.61676" />
<path
d="M 529.59463,513.57498 Z"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:360px;line-height:125%;font-family:'Product Sans';-inkscape-font-specification:'Product Sans Bold';letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.31883px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="path915"
inkscape:connector-curvature="0" />
<path
d="M 856.00418,513.57498 Z"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:360px;line-height:125%;font-family:'Product Sans';-inkscape-font-specification:'Product Sans Bold';letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1.31883px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
id="path919"
inkscape:connector-curvature="0" />
</g>
</svg>
| website/diagrams/ui/article-hero-image.svg/0 | {
"file_path": "website/diagrams/ui/article-hero-image.svg",
"repo_id": "website",
"token_count": 5969
} | 1,429 |
// Copyright 2017 The Chromium 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 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart' show timeDilation;
class StaggerAnimation extends StatelessWidget {
StaggerAnimation({super.key, required this.controller})
:
// Each animation defined here transforms its value during the subset
// of the controller's duration defined by the animation's interval.
// For example the opacity animation transforms its value during
// the first 10% of the controller's duration.
opacity = Tween<double>(
begin: 0.0,
end: 1.0,
).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(
0.0,
0.100,
curve: Curves.ease,
),
),
),
width = Tween<double>(
begin: 50.0,
end: 150.0,
).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(
0.125,
0.250,
curve: Curves.ease,
),
),
),
height = Tween<double>(begin: 50.0, end: 150.0).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(
0.250,
0.375,
curve: Curves.ease,
),
),
),
padding = EdgeInsetsTween(
begin: const EdgeInsets.only(bottom: 16),
end: const EdgeInsets.only(bottom: 75),
).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(
0.250,
0.375,
curve: Curves.ease,
),
),
),
borderRadius = BorderRadiusTween(
begin: BorderRadius.circular(4),
end: BorderRadius.circular(75),
).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(
0.375,
0.500,
curve: Curves.ease,
),
),
),
color = ColorTween(
begin: Colors.indigo[100],
end: Colors.orange[400],
).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(
0.500,
0.750,
curve: Curves.ease,
),
),
);
final Animation<double> controller;
final Animation<double> opacity;
final Animation<double> width;
final Animation<double> height;
final Animation<EdgeInsets> padding;
final Animation<BorderRadius?> borderRadius;
final Animation<Color?> color;
// This function is called each time the controller "ticks" a new frame.
// When it runs, all of the animation's values will have been
// updated to reflect the controller's current value.
Widget _buildAnimation(BuildContext context, Widget? child) {
return Container(
padding: padding.value,
alignment: Alignment.bottomCenter,
child: Opacity(
opacity: opacity.value,
child: Container(
width: width.value,
height: height.value,
decoration: BoxDecoration(
color: color.value,
border: Border.all(
color: Colors.indigo[300]!,
width: 3,
),
borderRadius: borderRadius.value,
),
),
),
);
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
builder: _buildAnimation,
animation: controller,
);
}
}
class StaggerDemo extends StatefulWidget {
const StaggerDemo({super.key});
@override
State<StaggerDemo> createState() => _StaggerDemoState();
}
class _StaggerDemoState extends State<StaggerDemo>
with TickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 2000),
vsync: this,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<void> _playAnimation() async {
try {
await _controller.forward().orCancel;
await _controller.reverse().orCancel;
} on TickerCanceled {
// The animation got canceled, probably because we were disposed.
}
}
@override
Widget build(BuildContext context) {
timeDilation = 10.0; // 1.0 is normal animation speed.
return Scaffold(
appBar: AppBar(
title: const Text('Staggered Animation'),
),
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
_playAnimation();
},
child: Center(
child: Container(
width: 300,
height: 300,
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.1),
border: Border.all(
color: Colors.black.withOpacity(0.5),
),
),
child: StaggerAnimation(controller: _controller.view),
),
),
),
);
}
}
void main() {
runApp(
const MaterialApp(
home: StaggerDemo(),
),
);
}
| website/examples/_animation/basic_staggered_animation/lib/main.dart/0 | {
"file_path": "website/examples/_animation/basic_staggered_animation/lib/main.dart",
"repo_id": "website",
"token_count": 2550
} | 1,430 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
// A "radial transition" that slightly differs from the Material
// motion spec:
// - The circular *and* the rectangular clips change as t goes from
// 0.0 to 1.0. (The rectangular clip doesn't change in the
// Material motion spec.)
// - This requires adding LayoutBuilders and computing t.
// - The key is that the rectangular clip grows more slowly than the
// circular clip.
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart' show timeDilation;
class Photo extends StatelessWidget {
const Photo({super.key, required this.photo, this.onTap});
final String photo;
final VoidCallback? onTap;
@override
Widget build(BuildContext context) {
return Material(
// Slightly opaque color appears where the image has transparency.
color: Theme.of(context).primaryColor.withOpacity(0.25),
child: InkWell(
onTap: onTap,
child: LayoutBuilder(
builder: (context, size) {
return Image.asset(
photo,
fit: BoxFit.contain,
);
},
),
),
);
}
}
class RadialExpansion extends StatelessWidget {
RadialExpansion({
super.key,
required this.minRadius,
required this.maxRadius,
this.child,
}) : clipTween = Tween<double>(
begin: 2.0 * minRadius,
end: 2.0 * (maxRadius / math.sqrt2),
);
final double minRadius;
final double maxRadius;
final Tween<double> clipTween;
final Widget? child;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, size) {
final double t =
(size.biggest.width / 2.0 - minRadius) / (maxRadius - minRadius);
final double rectClipExtent = clipTween.transform(t);
return ClipOval(
child: Center(
child: SizedBox(
width: rectClipExtent,
height: rectClipExtent,
child: ClipRect(
child: child,
),
),
),
);
},
);
}
}
class RadialExpansionDemo extends StatelessWidget {
const RadialExpansionDemo({super.key});
static const double kMinRadius = 32.0;
static const double kMaxRadius = 128.0;
static const opacityCurve = Interval(0.0, 0.75, curve: Curves.fastOutSlowIn);
RectTween _createRectTween(Rect? begin, Rect? end) {
return MaterialRectCenterArcTween(begin: begin, end: end);
}
Widget _buildPage(
BuildContext context, String imageName, String description) {
return Container(
color: Theme.of(context).canvasColor,
child: Center(
child: Card(
elevation: 8,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: kMaxRadius * 2.0,
height: kMaxRadius * 2.0,
child: Hero(
createRectTween: _createRectTween,
tag: imageName,
child: RadialExpansion(
minRadius: kMinRadius,
maxRadius: kMaxRadius,
child: Photo(
photo: imageName,
onTap: () {
Navigator.of(context).pop();
},
),
),
),
),
Text(
description,
style: const TextStyle(fontWeight: FontWeight.bold),
textScaler: const TextScaler.linear(3),
),
const SizedBox(height: 16),
],
),
),
),
);
}
Widget _buildHero(
BuildContext context,
String imageName,
String description,
) {
return SizedBox(
width: kMinRadius * 2.0,
height: kMinRadius * 2.0,
child: Hero(
createRectTween: _createRectTween,
tag: imageName,
child: RadialExpansion(
minRadius: kMinRadius,
maxRadius: kMaxRadius,
child: Photo(
photo: imageName,
onTap: () {
Navigator.of(context).push(
PageRouteBuilder<void>(
pageBuilder: (context, animation, secondaryAnimation) {
return AnimatedBuilder(
animation: animation,
builder: (context, child) {
return Opacity(
opacity: opacityCurve.transform(animation.value),
child: _buildPage(context, imageName, description),
);
},
);
},
),
);
},
),
),
),
);
}
@override
Widget build(BuildContext context) {
timeDilation = 15.0; // 1.0 is normal animation speed.
return Scaffold(
appBar: AppBar(
title: const Text('Radial Transition Demo'),
),
body: Container(
padding: const EdgeInsets.all(32),
alignment: FractionalOffset.bottomLeft,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_buildHero(context, 'images/chair-alpha.png', 'Chair'),
_buildHero(context, 'images/binoculars-alpha.png', 'Binoculars'),
_buildHero(context, 'images/beachball-alpha.png', 'Beach ball'),
],
),
),
);
}
}
void main() {
runApp(
const MaterialApp(
home: RadialExpansionDemo(),
),
);
}
| website/examples/_animation/radial_hero_animation_animate_rectclip/lib/main.dart/0 | {
"file_path": "website/examples/_animation/radial_hero_animation_animate_rectclip/lib/main.dart",
"repo_id": "website",
"token_count": 2814
} | 1,431 |
// Basic Flutter widget test.
// Learn more at https://docs.flutter.dev/testing/overview#widget-tests.
import 'package:animation/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Codelab smoke test', (tester) async {
await tester.pumpWidget(const LogoApp());
expect(find.byType(FlutterLogo), findsOneWidget);
});
}
| website/examples/animation/animate5/test/widget_test.dart/0 | {
"file_path": "website/examples/animation/animate5/test/widget_test.dart",
"repo_id": "website",
"token_count": 142
} | 1,432 |
// 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.
// ignore_for_file: avoid_init_to_null
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
// #docregion MyApp
class MyApp extends StatelessWidget {
const MyApp({super.key});
final int anInt = 3; // Can't be null.
final int? aNullableInt = null; // Can be null.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Nullable Fields Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Nullable Fields Demo'),
),
body: Center(
child: Column(
children: [
Text('anInt is $anInt.'),
Text('aNullableInt is $aNullableInt.'),
],
),
),
),
);
}
}
// #enddocregion MyApp
| website/examples/basics/lib/main.dart/0 | {
"file_path": "website/examples/basics/lib/main.dart",
"repo_id": "website",
"token_count": 387
} | 1,433 |
import 'package:flutter/material.dart';
// #docregion import
import 'package:flutter/physics.dart';
// #enddocregion import
void main() {
runApp(const MaterialApp(home: PhysicsCardDragDemo()));
}
class PhysicsCardDragDemo extends StatelessWidget {
const PhysicsCardDragDemo({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: const DraggableCard(
child: FlutterLogo(
size: 128,
),
),
);
}
}
/// A draggable card that moves back to [Alignment.center] when it's
/// released.
class DraggableCard extends StatefulWidget {
const DraggableCard({required this.child, super.key});
final Widget child;
@override
State<DraggableCard> createState() => _DraggableCardState();
}
class _DraggableCardState extends State<DraggableCard>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
/// The alignment of the card as it is dragged or being animated.
///
/// While the card is being dragged, this value is set to the values computed
/// in the GestureDetector onPanUpdate callback. If the animation is running,
/// this value is set to the value of the [_animation].
Alignment _dragAlignment = Alignment.center;
late Animation<Alignment> _animation;
// #docregion runAnimation
/// Calculates and runs a [SpringSimulation].
void _runAnimation(Offset pixelsPerSecond, Size size) {
_animation = _controller.drive(
AlignmentTween(
begin: _dragAlignment,
end: Alignment.center,
),
);
// Calculate the velocity relative to the unit interval, [0,1],
// used by the animation controller.
final unitsPerSecondX = pixelsPerSecond.dx / size.width;
final unitsPerSecondY = pixelsPerSecond.dy / size.height;
final unitsPerSecond = Offset(unitsPerSecondX, unitsPerSecondY);
final unitVelocity = unitsPerSecond.distance;
const spring = SpringDescription(
mass: 30,
stiffness: 1,
damping: 1,
);
final simulation = SpringSimulation(spring, 0, 1, -unitVelocity);
_controller.animateWith(simulation);
}
// #enddocregion runAnimation
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this);
_controller.addListener(() {
setState(() {
_dragAlignment = _animation.value;
});
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return GestureDetector(
onPanDown: (details) {
_controller.stop();
},
onPanUpdate: (details) {
setState(() {
_dragAlignment += Alignment(
details.delta.dx / (size.width / 2),
details.delta.dy / (size.height / 2),
);
});
},
// #docregion onPanEnd
onPanEnd: (details) {
_runAnimation(details.velocity.pixelsPerSecond, size);
},
// #enddocregion onPanEnd
child: Align(
alignment: _dragAlignment,
child: Card(
child: widget.child,
),
),
);
}
}
| website/examples/cookbook/animation/physics_simulation/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/animation/physics_simulation/lib/main.dart",
"repo_id": "website",
"token_count": 1210
} | 1,434 |
import 'package:flutter/material.dart';
class OrientationList1 extends StatelessWidget {
final String title;
const OrientationList1({super.key, required this.title});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: OrientationBuilder(
builder: (context, orientation) {
// #docregion GridViewCount
return GridView.count(
// A list with 2 columns
crossAxisCount: 2,
// ...
);
// #enddocregion GridViewCount
},
),
);
}
}
class OrientationList2 extends StatelessWidget {
final String title;
const OrientationList2({super.key, required this.title});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
// #docregion OrientationBuilder
body: OrientationBuilder(
builder: (context, orientation) {
return GridView.count(
// Create a grid with 2 columns in portrait mode,
// or 3 columns in landscape mode.
crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
);
},
),
// #enddocregion OrientationBuilder
);
}
}
| website/examples/cookbook/design/orientation/lib/partials.dart/0 | {
"file_path": "website/examples/cookbook/design/orientation/lib/partials.dart",
"repo_id": "website",
"token_count": 516
} | 1,435 |
name: themes
description: Sample code for themes cookbook recipe.
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
google_fonts: ^6.1.0
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter:
uses-material-design: true
| website/examples/cookbook/design/themes/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/design/themes/pubspec.yaml",
"repo_id": "website",
"token_count": 102
} | 1,436 |
import 'package:flutter/material.dart';
@immutable
class ExpandableFab extends StatefulWidget {
const ExpandableFab({
super.key,
this.initialOpen,
required this.distance,
required this.children,
});
final bool? initialOpen;
final double distance;
final List<Widget> children;
@override
State<ExpandableFab> createState() => _ExpandableFabState();
}
// #docregion ExpandableFabState
class _ExpandableFabState extends State<ExpandableFab> {
bool _open = false;
@override
void initState() {
super.initState();
_open = widget.initialOpen ?? false;
}
void _toggle() {
setState(() {
_open = !_open;
});
}
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: Stack(
alignment: Alignment.bottomRight,
clipBehavior: Clip.none,
children: [
_buildTapToCloseFab(),
_buildTapToOpenFab(),
],
),
);
}
Widget _buildTapToCloseFab() {
return SizedBox(
width: 56,
height: 56,
child: Center(
child: Material(
shape: const CircleBorder(),
clipBehavior: Clip.antiAlias,
elevation: 4,
child: InkWell(
onTap: _toggle,
child: Padding(
padding: const EdgeInsets.all(8),
child: Icon(
Icons.close,
color: Theme.of(context).primaryColor,
),
),
),
),
),
);
}
Widget _buildTapToOpenFab() {
return IgnorePointer(
ignoring: _open,
child: AnimatedContainer(
transformAlignment: Alignment.center,
transform: Matrix4.diagonal3Values(
_open ? 0.7 : 1.0,
_open ? 0.7 : 1.0,
1.0,
),
duration: const Duration(milliseconds: 250),
curve: const Interval(0.0, 0.5, curve: Curves.easeOut),
child: AnimatedOpacity(
opacity: _open ? 0.0 : 1.0,
curve: const Interval(0.25, 1.0, curve: Curves.easeInOut),
duration: const Duration(milliseconds: 250),
child: FloatingActionButton(
onPressed: _toggle,
child: const Icon(Icons.create),
),
),
),
);
}
}
// #enddocregion ExpandableFabState
| website/examples/cookbook/effects/expandable_fab/lib/excerpt2.dart/0 | {
"file_path": "website/examples/cookbook/effects/expandable_fab/lib/excerpt2.dart",
"repo_id": "website",
"token_count": 1077
} | 1,437 |
import 'package:flutter/material.dart';
@immutable
class SetupFlow extends StatefulWidget {
static SetupFlowState of(BuildContext context) {
return context.findAncestorStateOfType<SetupFlowState>()!;
}
const SetupFlow({
super.key,
required this.setupPageRoute,
});
final String setupPageRoute;
@override
State<SetupFlow> createState() => SetupFlowState();
}
class SetupFlowState extends State<SetupFlow> {
@override
void initState() {
super.initState();
}
// #docregion PromptUser
Future<void> _onExitPressed() async {
final isConfirmed = await _isExitDesired();
if (isConfirmed && mounted) {
_exitSetup();
}
}
Future<bool> _isExitDesired() async {
return await showDialog<bool>(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Are you sure?'),
content: const Text(
'If you exit device setup, your progress will be lost.'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: const Text('Leave'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: const Text('Stay'),
),
],
);
}) ??
false;
}
void _exitSetup() {
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: false,
onPopInvoked: (didPop) async {
if (didPop) return;
if (await _isExitDesired() && context.mounted) {
_exitSetup();
}
},
child: Scaffold(
appBar: _buildFlowAppBar(),
body: const SizedBox(),
),
);
}
PreferredSizeWidget _buildFlowAppBar() {
return AppBar(
leading: IconButton(
onPressed: _onExitPressed,
icon: const Icon(Icons.chevron_left),
),
title: const Text('Bulb Setup'),
);
}
// #enddocregion PromptUser
}
| website/examples/cookbook/effects/nested_nav/lib/prompt_user.dart/0 | {
"file_path": "website/examples/cookbook/effects/nested_nav/lib/prompt_user.dart",
"repo_id": "website",
"token_count": 1074
} | 1,438 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.