text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
package com.example.ffigen_app_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity()
| codelabs/ffigen_codelab/step_03/example/android/app/src/main/kotlin/com/example/ffigen_app_example/MainActivity.kt/0 | {
"file_path": "codelabs/ffigen_codelab/step_03/example/android/app/src/main/kotlin/com/example/ffigen_app_example/MainActivity.kt",
"repo_id": "codelabs",
"token_count": 38
} | 39 |
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "example",
"cwd": "example",
"request": "launch",
"type": "dart"
}
]
}
| codelabs/ffigen_codelab/step_05/.vscode/launch.json/0 | {
"file_path": "codelabs/ffigen_codelab/step_05/.vscode/launch.json",
"repo_id": "codelabs",
"token_count": 179
} | 40 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint ffigen_app.podspec` to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'ffigen_app'
s.version = '0.0.1'
s.summary = 'A new Flutter FFI plugin project.'
s.description = <<-DESC
A new Flutter FFI plugin project.
DESC
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => '[email protected]' }
# This will ensure the source files in Classes/ are included in the native
# builds of apps using this FFI plugin. Podspec does not support relative
# paths, so Classes contains a forwarder C file that relatively imports
# `../src/*` so that the C sources can be shared among all target platforms.
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
s.platform = :ios, '11.0'
# Flutter.framework does not contain a i386 slice.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
s.swift_version = '5.0'
end
| codelabs/ffigen_codelab/step_05/ios/ffigen_app.podspec/0 | {
"file_path": "codelabs/ffigen_codelab/step_05/ios/ffigen_app.podspec",
"repo_id": "codelabs",
"token_count": 478
} | 41 |
// Relative import to be able to reuse the C sources.
// See the comment in ../ffigen_app.podspec for more information.
#include "../../src/duktape.c"
| codelabs/ffigen_codelab/step_06/ios/Classes/duktape.c/0 | {
"file_path": "codelabs/ffigen_codelab/step_06/ios/Classes/duktape.c",
"repo_id": "codelabs",
"token_count": 46
} | 42 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/firebase-auth-flutterfire-ui/start/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/firebase-auth-flutterfire-ui/start/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 43 |
{
"indexes": [],
"fieldOverrides": []
}
| codelabs/firebase-emulator-suite/complete/firestore.indexes.json/0 | {
"file_path": "codelabs/firebase-emulator-suite/complete/firestore.indexes.json",
"repo_id": "codelabs",
"token_count": 21
} | 44 |
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'app_state.dart';
class LoggedOutView extends StatelessWidget {
final AppState state;
const LoggedOutView({super.key, required this.state});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Firebase Emulator Suite Codelab'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Please log in',
style: Theme.of(context).textTheme.displaySmall,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: FilledButton(
onPressed: () async {
await state.logIn('[email protected]', 'dashword').then((_) {
if (state.user != null) {
context.go('/');
}
});
},
child: const Text('Log In'),
),
),
],
),
),
);
}
}
| codelabs/firebase-emulator-suite/complete/lib/logged_out_view.dart/0 | {
"file_path": "codelabs/firebase-emulator-suite/complete/lib/logged_out_view.dart",
"repo_id": "codelabs",
"token_count": 602
} | 45 |
buildscript {
ext.kotlin_version = '1.7.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
| codelabs/firebase-emulator-suite/start/android/build.gradle/0 | {
"file_path": "codelabs/firebase-emulator-suite/start/android/build.gradle",
"repo_id": "codelabs",
"token_count": 232
} | 46 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/firebase-get-to-know-flutter/step_02/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_02/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 47 |
// Copyright 2022 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/material.dart';
import 'guest_book_message.dart';
import 'src/widgets.dart';
class GuestBook extends StatefulWidget {
const GuestBook({
super.key,
required this.addMessage,
required this.messages,
});
final FutureOr<void> Function(String message) addMessage;
final List<GuestBookMessage> messages;
@override
State<GuestBook> createState() => _GuestBookState();
}
class _GuestBookState extends State<GuestBook> {
final _formKey = GlobalKey<FormState>(debugLabel: '_GuestBookState');
final _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: _formKey,
child: Row(
children: [
Expanded(
child: TextFormField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Leave a message',
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Enter your message to continue';
}
return null;
},
),
),
const SizedBox(width: 8),
StyledButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
await widget.addMessage(_controller.text);
_controller.clear();
}
},
child: const Row(
children: [
Icon(Icons.send),
SizedBox(width: 4),
Text('SEND'),
],
),
),
],
),
),
),
const SizedBox(height: 8),
for (var message in widget.messages)
Paragraph('${message.name}: ${message.message}'),
const SizedBox(height: 8),
],
);
}
}
| codelabs/firebase-get-to-know-flutter/step_09/lib/guest_book.dart/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_09/lib/guest_book.dart",
"repo_id": "codelabs",
"token_count": 1260
} | 48 |
// Copyright 2022 Google LLC
//
// 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
//
// https://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 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'window_to_front_method_channel.dart';
abstract class WindowToFrontPlatform extends PlatformInterface {
/// Constructs a WindowToFrontPlatform.
WindowToFrontPlatform() : super(token: _token);
static final Object _token = Object();
static WindowToFrontPlatform _instance = MethodChannelWindowToFront();
/// The default instance of [WindowToFrontPlatform] to use.
///
/// Defaults to [MethodChannelWindowToFront].
static WindowToFrontPlatform get instance => _instance;
/// Platform-specific implementations should set this with their own
/// platform-specific class that extends [WindowToFrontPlatform] when
/// they register themselves.
static set instance(WindowToFrontPlatform instance) {
PlatformInterface.verifyToken(instance, _token);
_instance = instance;
}
Future<void> activate() {
throw UnimplementedError('activate() has not been implemented.');
}
}
| codelabs/github-client/window_to_front/lib/window_to_front_platform_interface.dart/0 | {
"file_path": "codelabs/github-client/window_to_front/lib/window_to_front_platform_interface.dart",
"repo_id": "codelabs",
"token_count": 406
} | 49 |
/*
* Copyright 2019 Google LLC
*
* 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
*
* https://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:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:http/http.dart' as http;
import 'package:json_annotation/json_annotation.dart';
part 'locations.g.dart';
@JsonSerializable()
class LatLng {
LatLng({
required this.lat,
required this.lng,
});
factory LatLng.fromJson(Map<String, dynamic> json) => _$LatLngFromJson(json);
Map<String, dynamic> toJson() => _$LatLngToJson(this);
final double lat;
final double lng;
}
@JsonSerializable()
class Region {
Region({
required this.coords,
required this.id,
required this.name,
required this.zoom,
});
factory Region.fromJson(Map<String, dynamic> json) => _$RegionFromJson(json);
Map<String, dynamic> toJson() => _$RegionToJson(this);
final LatLng coords;
final String id;
final String name;
final double zoom;
}
@JsonSerializable()
class Office {
Office({
required this.address,
required this.id,
required this.image,
required this.lat,
required this.lng,
required this.name,
required this.phone,
required this.region,
});
factory Office.fromJson(Map<String, dynamic> json) => _$OfficeFromJson(json);
Map<String, dynamic> toJson() => _$OfficeToJson(this);
final String address;
final String id;
final String image;
final double lat;
final double lng;
final String name;
final String phone;
final String region;
}
@JsonSerializable()
class Locations {
Locations({
required this.offices,
required this.regions,
});
factory Locations.fromJson(Map<String, dynamic> json) =>
_$LocationsFromJson(json);
Map<String, dynamic> toJson() => _$LocationsToJson(this);
final List<Office> offices;
final List<Region> regions;
}
Future<Locations> getGoogleOffices() async {
const googleLocationsURL = 'https://about.google/static/data/locations.json';
// Retrieve the locations of Google offices
try {
final response = await http.get(Uri.parse(googleLocationsURL));
if (response.statusCode == 200) {
return Locations.fromJson(
json.decode(response.body) as Map<String, dynamic>);
}
} catch (e) {
if (kDebugMode) {
print(e);
}
}
// Fallback for when the above HTTP request fails.
return Locations.fromJson(
json.decode(
await rootBundle.loadString('assets/locations.json'),
) as Map<String, dynamic>,
);
}
| codelabs/google-maps-in-flutter/step_5/lib/src/locations.dart/0 | {
"file_path": "codelabs/google-maps-in-flutter/step_5/lib/src/locations.dart",
"repo_id": "codelabs",
"token_count": 1036
} | 50 |
import 'package:flutter/material.dart';
LinearGradient shimmerGradient = const LinearGradient(
colors: <Color>[
Color(0xFFEBEBF4),
Color(0xFFF4F4F4),
Color(0xFFEBEBF4),
],
stops: <double>[
0.1,
0.3,
0.4,
],
begin: Alignment(-1.0, -0.3),
end: Alignment(1.0, 0.3),
);
| codelabs/haiku_generator/finished/lib/widgets/shimmer_gradient.dart/0 | {
"file_path": "codelabs/haiku_generator/finished/lib/widgets/shimmer_gradient.dart",
"repo_id": "codelabs",
"token_count": 149
} | 51 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/haiku_generator/finished/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/haiku_generator/finished/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 52 |
import '../data/repositories/poem_repository_impl.dart';
import '../domain/repositories/abstract/poem_repository.dart';
class PoemController {
final PoemRepository poemRepository = PoemRepositoryImpl();
Future<String> getPoem(String productName) {
return poemRepository.getPoems(productName);
}
}
| codelabs/haiku_generator/step0/lib/controller/poem_controller.dart/0 | {
"file_path": "codelabs/haiku_generator/step0/lib/controller/poem_controller.dart",
"repo_id": "codelabs",
"token_count": 107
} | 53 |
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter_test/flutter_test.dart';
import 'package:haiku_generator/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that the widgets are there
expect(find.text('Choose a Google product here:'), findsOneWidget);
expect(find.text('Generate haiku!'), findsOneWidget);
});
}
| codelabs/haiku_generator/step0/test/widget_test.dart/0 | {
"file_path": "codelabs/haiku_generator/step0/test/widget_test.dart",
"repo_id": "codelabs",
"token_count": 238
} | 54 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/haiku_generator/step1/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/haiku_generator/step1/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 55 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/haiku_generator/step3/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/haiku_generator/step3/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 56 |
<?xml version="1.0" encoding="utf-8"?><!--
Background for views inside widgets to make the rounded corners based on the
appWidgetInnerRadius attribute value
-->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="?attr/appWidgetInnerRadius" />
<solid android:color="?android:attr/colorAccent" />
</shape> | codelabs/homescreen_codelab/step_04/android/app/src/main/res/drawable-v21/app_widget_inner_view_background.xml/0 | {
"file_path": "codelabs/homescreen_codelab/step_04/android/app/src/main/res/drawable-v21/app_widget_inner_view_background.xml",
"repo_id": "codelabs",
"token_count": 123
} | 57 |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--
Refer to App Widget Documentation for margin information
http://developer.android.com/guide/topics/appwidgets/index.html#CreatingLayout
-->
<dimen name="widget_margin">0dp</dimen>
</resources> | codelabs/homescreen_codelab/step_04/android/app/src/main/res/values/dimens.xml/0 | {
"file_path": "codelabs/homescreen_codelab/step_04/android/app/src/main/res/values/dimens.xml",
"repo_id": "codelabs",
"token_count": 88
} | 58 |
{
"images" : [
{
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
| codelabs/homescreen_codelab/step_04/ios/NewsWidgets/Assets.xcassets/AppIcon.appiconset/Contents.json/0 | {
"file_path": "codelabs/homescreen_codelab/step_04/ios/NewsWidgets/Assets.xcassets/AppIcon.appiconset/Contents.json",
"repo_id": "codelabs",
"token_count": 97
} | 59 |
<?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>UIAppFonts</key>
<array>
<string>HanaleiFill-Regular.ttf</string>
</array>
<key>NSExtension</key>
<dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.widgetkit-extension</string>
</dict>
</dict>
</plist>
| codelabs/homescreen_codelab/step_05/ios/NewsWidgets/Info.plist/0 | {
"file_path": "codelabs/homescreen_codelab/step_05/ios/NewsWidgets/Info.plist",
"repo_id": "codelabs",
"token_count": 183
} | 60 |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--
Having themes.xml for night-v31 because of the priority order of the resource qualifiers.
-->
<style name="Theme.Android.AppWidgetContainerParent" parent="@android:style/Theme.DeviceDefault.DayNight">
<item name="appWidgetRadius">@android:dimen/system_app_widget_background_radius</item>
<item name="appWidgetInnerRadius">@android:dimen/system_app_widget_inner_radius</item>
</style>
</resources> | codelabs/homescreen_codelab/step_06/android/app/src/main/res/values-night-v31/themes.xml/0 | {
"file_path": "codelabs/homescreen_codelab/step_06/android/app/src/main/res/values-night-v31/themes.xml",
"repo_id": "codelabs",
"token_count": 167
} | 61 |
#import "GeneratedPluginRegistrant.h"
| codelabs/homescreen_codelab/step_06/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/homescreen_codelab/step_06/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 62 |
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:google_sign_in/google_sign_in.dart';
import '../firebase_options.dart';
import '../model/firebase_state.dart';
class FirebaseNotifier extends ChangeNotifier {
bool loggedIn = false;
FirebaseState state = FirebaseState.loading;
bool isLoggingIn = false;
FirebaseNotifier() {
load();
}
late final Completer<bool> _isInitialized = Completer();
Future<FirebaseFirestore> get firestore async {
var isInitialized = await _isInitialized.future;
if (!isInitialized) {
throw Exception('Firebase is not initialized');
}
return FirebaseFirestore.instance;
}
User? get user => FirebaseAuth.instance.currentUser;
Future<void> load() async {
try {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
loggedIn = FirebaseAuth.instance.currentUser != null;
state = FirebaseState.available;
_isInitialized.complete(true);
notifyListeners();
} catch (e) {
state = FirebaseState.notAvailable;
_isInitialized.complete(false);
notifyListeners();
}
}
Future<void> login() async {
isLoggingIn = true;
notifyListeners();
// Trigger the authentication flow
try {
final googleUser = await GoogleSignIn().signIn();
if (googleUser == null) {
isLoggingIn = false;
notifyListeners();
return;
}
// Obtain the auth details from the request
final googleAuth = await googleUser.authentication;
// Create a new credential
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
// Once signed in, return the UserCredential
await FirebaseAuth.instance.signInWithCredential(credential);
loggedIn = true;
isLoggingIn = false;
notifyListeners();
} catch (e) {
isLoggingIn = false;
notifyListeners();
return;
}
}
}
| codelabs/in_app_purchases/complete/app/lib/logic/firebase_notifier.dart/0 | {
"file_path": "codelabs/in_app_purchases/complete/app/lib/logic/firebase_notifier.dart",
"repo_id": "codelabs",
"token_count": 824
} | 63 |
include: package:lints/recommended.yaml
analyzer:
language:
strict-casts: true
strict-inference: true
linter:
rules:
avoid_types_on_closure_parameters: true
avoid_void_async: true
cancel_subscriptions: true
close_sinks: true
directives_ordering: true
package_api_docs: true
package_prefixed_library_names: true
prefer_relative_imports: true
prefer_single_quotes: true
test_types_in_equals: true
throw_in_finally: true
unawaited_futures: true
unnecessary_statements: true
use_super_parameters: true
| codelabs/in_app_purchases/complete/dart-backend/analysis_options.yaml/0 | {
"file_path": "codelabs/in_app_purchases/complete/dart-backend/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 217
} | 64 |
#import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>
@interface AppDelegate : FlutterAppDelegate
@end
| codelabs/in_app_purchases/step_00/app/ios/Runner/AppDelegate.h/0 | {
"file_path": "codelabs/in_app_purchases/step_00/app/ios/Runner/AppDelegate.h",
"repo_id": "codelabs",
"token_count": 41
} | 65 |
// File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, kIsWeb, TargetPlatform;
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for web - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
case TargetPlatform.macOS:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for macos - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.windows:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for windows - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.linux:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for linux - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions android = FirebaseOptions(
apiKey: 'API KEY',
appId: 'APP ID',
messagingSenderId: 'SENDER ID',
projectId: 'PROJECT ID',
storageBucket: 'STORAGE BUCKET',
);
static const FirebaseOptions ios = FirebaseOptions(
apiKey: 'API KEY',
appId: 'APP ID',
messagingSenderId: 'SENDER ID',
projectId: 'PROJECT ID',
storageBucket: 'STORAGE BUCKET',
iosClientId: 'CLIENT ID',
iosBundleId: 'BUNDLE ID',
);
}
| codelabs/in_app_purchases/step_00/app/lib/firebase_options.dart/0 | {
"file_path": "codelabs/in_app_purchases/step_00/app/lib/firebase_options.dart",
"repo_id": "codelabs",
"token_count": 831
} | 66 |
# Defines what ignore for gcloud deploy
# Files and directories created by pub.
.dart_tool/
.packages
# Conventional directory for build output.
build/
| codelabs/in_app_purchases/step_00/dart-backend/.gcloudignore/0 | {
"file_path": "codelabs/in_app_purchases/step_00/dart-backend/.gcloudignore",
"repo_id": "codelabs",
"token_count": 43
} | 67 |
include: ../../../analysis_options.yaml
| codelabs/in_app_purchases/step_10/app/analysis_options.yaml/0 | {
"file_path": "codelabs/in_app_purchases/step_10/app/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 13
} | 68 |
buildscript {
ext.kotlin_version = '1.6.21'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.4'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.10'
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| codelabs/in_app_purchases/step_10/app/android/build.gradle/0 | {
"file_path": "codelabs/in_app_purchases/step_10/app/android/build.gradle",
"repo_id": "codelabs",
"token_count": 286
} | 69 |
#import "GeneratedPluginRegistrant.h"
| codelabs/in_app_purchases/step_10/app/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/in_app_purchases/step_10/app/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 70 |
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import '../constants.dart';
import '../logic/firebase_notifier.dart';
import '../model/past_purchase.dart';
class IAPRepo extends ChangeNotifier {
late FirebaseFirestore _firestore;
late FirebaseAuth _auth;
bool get isLoggedIn => _user != null;
User? _user;
bool hasActiveSubscription = false;
bool hasUpgrade = false;
List<PastPurchase> purchases = [];
StreamSubscription<User?>? _userSubscription;
StreamSubscription<QuerySnapshot>? _purchaseSubscription;
IAPRepo(FirebaseNotifier firebaseNotifier) {
firebaseNotifier.firestore.then((value) {
_auth = FirebaseAuth.instance;
_firestore = value;
updatePurchases();
listenToLogin();
});
}
void listenToLogin() {
_user = _auth.currentUser;
_userSubscription = FirebaseAuth.instance.authStateChanges().listen((user) {
_user = user;
updatePurchases();
});
}
void updatePurchases() {
_purchaseSubscription?.cancel();
var user = _user;
if (user == null) {
purchases = [];
hasActiveSubscription = false;
hasUpgrade = false;
return;
}
var purchaseStream = _firestore
.collection('purchases')
.where('userId', isEqualTo: user.uid)
.snapshots();
_purchaseSubscription = purchaseStream.listen((snapshot) {
purchases = snapshot.docs.map((document) {
var data = document.data();
return PastPurchase.fromJson(data);
}).toList();
hasActiveSubscription = purchases.any((element) =>
element.productId == storeKeySubscription &&
element.status != Status.expired);
hasUpgrade = purchases.any(
(element) => element.productId == storeKeyUpgrade,
);
notifyListeners();
});
}
@override
void dispose() {
_userSubscription?.cancel();
_purchaseSubscription?.cancel();
super.dispose();
}
}
| codelabs/in_app_purchases/step_10/app/lib/repo/iap_repo.dart/0 | {
"file_path": "codelabs/in_app_purchases/step_10/app/lib/repo/iap_repo.dart",
"repo_id": "codelabs",
"token_count": 781
} | 71 |
import 'products.dart';
/// Generic purchase handler,
/// must be implemented for Google Play and Apple Store
abstract class PurchaseHandler {
/// Verify if purchase is valid and update the database
Future<bool> verifyPurchase({
required String userId,
required ProductData productData,
required String token,
}) async {
switch (productData.type) {
case ProductType.subscription:
return handleSubscription(
userId: userId,
productData: productData,
token: token,
);
case ProductType.nonSubscription:
return handleNonSubscription(
userId: userId,
productData: productData,
token: token,
);
}
}
/// Verify if non-subscription purchase (aka consumable) is valid
/// and update the database
Future<bool> handleNonSubscription({
required String userId,
required ProductData productData,
required String token,
});
/// Verify if subscription purchase (aka non-consumable) is valid
/// and update the database
Future<bool> handleSubscription({
required String userId,
required ProductData productData,
required String token,
});
}
| codelabs/in_app_purchases/step_10/dart-backend/lib/purchase_handler.dart/0 | {
"file_path": "codelabs/in_app_purchases/step_10/dart-backend/lib/purchase_handler.dart",
"repo_id": "codelabs",
"token_count": 401
} | 72 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:namer_app/main.dart';
void main() {
testWidgets('App starts', (WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
expect(find.text('A random AWESOME idea:'), findsOneWidget);
});
testWidgets('Tapping button changes word pair', (WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
String findWordPair() {
final wordPairTextWidget = tester
// Get all Text widgets...
.widgetList<Text>(find.byType(Text))
// ... skip one ('A random AWESOME idea:') ...
.skip(1)
// ... and take the first after it.
.first;
return wordPairTextWidget.data!;
}
// Tap several times and keep a list of word pair values.
const tryCount = 5;
final pairs = <String>[
findWordPair(),
];
for (var i = 1; i < tryCount; i++) {
await tester.tap(find.text('Next'));
await tester.pumpAndSettle();
pairs.add(findWordPair());
}
expect(
// Converting the list to a set to remove duplicates.
pairs.toSet(),
// An occassional duplicate word pair is okay and expected.
// We only fail this test when there is zero variance - all the
// word pairs are the same, even though we clicked 'Next' several times.
hasLength(greaterThan(1)),
reason: 'After clicking $tryCount times, '
'the app should have generated at least two different word pairs. '
'Instead, the app showed these: $pairs. '
'That almost certainly means that the word pair is not being '
'randomly generated at all. The button does not work.',
);
});
}
| codelabs/namer/step_04_b_behavior/test/widget_test.dart/0 | {
"file_path": "codelabs/namer/step_04_b_behavior/test/widget_test.dart",
"repo_id": "codelabs",
"token_count": 671
} | 73 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/namer/step_05_e_text_style/android/gradle.properties/0 | {
"file_path": "codelabs/namer/step_05_e_text_style/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 74 |
#include "Generated.xcconfig"
| codelabs/namer/step_05_g_center_vertical/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_g_center_vertical/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 75 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/namer/step_05_g_center_vertical/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_g_center_vertical/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 76 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/namer/step_05_h_center_horizontal/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_h_center_horizontal/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 77 |
#include "Generated.xcconfig"
| codelabs/namer/step_06_c_add_like_button/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_06_c_add_like_button/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 78 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/namer/step_06_c_add_like_button/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_06_c_add_like_button/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 79 |
#import "GeneratedPluginRegistrant.h"
| codelabs/namer/step_07_a_split_my_home_page/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/namer/step_07_a_split_my_home_page/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 80 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/namer/step_07_a_split_my_home_page/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_07_a_split_my_home_page/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 81 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/next-gen-ui/step_01/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/next-gen-ui/step_01/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 82 |
// Copyright 2023 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:ui';
class AssetPaths {
/// Images
static const String _images = 'assets/images';
static const String titleBgBase = '$_images/bg-base.jpg';
static const String titleBgReceive = '$_images/bg-light-receive.png';
static const String titleFgEmit = '$_images/fg-light-emit.png';
static const String titleFgReceive = '$_images/fg-light-receive.png';
static const String titleFgBase = '$_images/fg-base.png';
static const String titleMgEmit = '$_images/mg-light-emit.png';
static const String titleMgReceive = '$_images/mg-light-receive.png';
static const String titleMgBase = '$_images/mg-base.png';
static const String titleStartBtn = '$_images/button-start.png';
static const String titleStartBtnHover = '$_images/button-start-hover.png';
static const String titleStartArrow = '$_images/button-start-arrow.png';
static const String titleSelectedLeft = '$_images/select-left.png';
static const String titleSelectedRight = '$_images/select-right.png';
static const String pulseParticle = '$_images/particle3.png';
/// Shaders
static const String _shaders = 'assets/shaders';
static const String orbShader = '$_shaders/orb_shader.frag';
static const String uiShader = '$_shaders/ui_glitch.frag';
}
typedef FragmentPrograms = ({FragmentProgram orb, FragmentProgram ui});
Future<FragmentPrograms> loadFragmentPrograms() async => (
orb: (await _loadFragmentProgram(AssetPaths.orbShader)),
ui: (await _loadFragmentProgram(AssetPaths.uiShader)),
);
Future<FragmentProgram> _loadFragmentProgram(String path) async {
return (await FragmentProgram.fromAsset(path));
}
| codelabs/next-gen-ui/step_02_b/lib/assets.dart/0 | {
"file_path": "codelabs/next-gen-ui/step_02_b/lib/assets.dart",
"repo_id": "codelabs",
"token_count": 595
} | 83 |
package com.example.next_gen_ui
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity()
| codelabs/next-gen-ui/step_03_a/android/app/src/main/kotlin/com/example/next_gen_ui/MainActivity.kt/0 | {
"file_path": "codelabs/next-gen-ui/step_03_a/android/app/src/main/kotlin/com/example/next_gen_ui/MainActivity.kt",
"repo_id": "codelabs",
"token_count": 37
} | 84 |
// Copyright 2023 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.
#version 460 core
#include "common/common.glsl"
#include <flutter/runtime_effect.glsl>
#define RAY_STEPS 30
uniform vec2 uResolution;
uniform vec4 uPackedData;
float uTime = uPackedData[0];
float uExposure = uPackedData[1];
float uFov = uPackedData[2];
float uRoughness = uPackedData[3];
uniform float uMetalness;
uniform vec3 uLightDir;
uniform float uLightR;
uniform vec3 uLightLumP;
uniform vec3 uAlbedo;
uniform float uIor;
uniform float uLightQuadAtt;
uniform vec3 uAmbientLight;
uniform float uAmbientLightDepthFactor;
uniform float uEnergy;
out vec4 oColor;
float noise_2d(vec2 pos) {
vec2 g = floor(pos);
float a = hash_2d(g);
float b = hash_2d(g + vec2(1.0, 0.0));
float c = hash_2d(g + vec2(0.0, 1.0));
float d = hash_2d(g + vec2(1.0, 1.0));
vec2 fp = pos - g;
vec2 sfp = smoothstep(vec2(0.0), vec2(1.0), fp);
return a + (b - a) * sfp.x + (c - a) * sfp.y +
(a - b - c + d) * sfp.x * sfp.y;
}
vec3 closest_point_on_disc(vec3 center, vec3 normal, float radius, vec3 p) {
vec3 r = p - center;
vec3 pr = r - dot(r, normal) * normal;
return center + normalize(pr) * min(length(pr), radius);
}
// Compute area light illuminance from: Moving Frostbite to Physically Based
// Rendering 3.0, Siggraph 2014
float illuminanceSphereOrDisk(float cosTheta, float sinSigmaSqr) {
float cosThetaSqr = cosTheta * cosTheta;
float sinTheta = sqrt(1.0 - cosThetaSqr);
float illuminance = 0.0;
if (cosThetaSqr > sinSigmaSqr) {
illuminance = M_PI * sinSigmaSqr * clamp(cosTheta, 0.0, 1.0);
} else {
float x = sqrt(1.0 / sinSigmaSqr - 1.0);
float y = -x * (cosTheta / sinTheta);
float sinThetaSqrtY = sinTheta * sqrt(1.0 - y * y);
illuminance = (cosTheta * acos(y) - x * sinThetaSqrtY) * sinSigmaSqr +
atan(sinThetaSqrtY / x);
}
return max(illuminance, 0.0);
}
float evalIlluminanceDisk(vec3 N, vec3 L, vec3 lightN, float lightRadius,
float lightDistSqr) {
float cosTheta = dot(N, L);
float lightRSqr = lightRadius * lightRadius;
float sinSigmaSqr = lightRSqr / (lightRSqr + max(lightRSqr, lightDistSqr));
float illuminance = illuminanceSphereOrDisk(cosTheta, sinSigmaSqr) *
clamp(dot(lightN, -L), 0.0, 1.0);
return illuminance;
}
float distribution_ggx(vec3 N, vec3 H, float roughness) {
float a = roughness * roughness;
float a2 = a * a;
float NdotH = max(dot(N, H), 0.0);
float NdotH2 = NdotH * NdotH;
float nom = a2;
float denom = (NdotH2 * (a2 - 1.0) + 1.0);
denom = M_PI * denom * denom;
return nom / denom;
}
float geometry_schlick_ggx(float NdotV, float roughness) {
float r = (roughness + 1.0);
float k = (r * r) / 8.0;
float nom = NdotV;
float denom = NdotV * (1.0 - k) + k;
return nom / denom;
}
float geometry_smith(vec3 N, vec3 V, float cosTheta, float roughness) {
float NdotV = max(dot(N, V), 0.0);
float ggx2 = geometry_schlick_ggx(NdotV, roughness);
float ggx1 = geometry_schlick_ggx(cosTheta, roughness);
return ggx1 * ggx2;
}
vec3 fresnel_schlick(float cosTheta, vec3 F0) {
return F0 + (1.0 - F0) * pow(1.0 - cosTheta, 5.0);
}
vec3 brdf_eval(vec3 N, vec3 L, vec3 H, vec3 V, vec3 albedo, float roughness,
float metalness, vec3 Li) {
roughness = max(0.2, roughness);
float cosTheta = max(dot(N, L), 0.0);
// Diffuse color
vec3 F0 = vec3(0.04);
F0 = mix(F0, albedo, metalness);
float NDF = distribution_ggx(N, H, roughness);
float G = geometry_smith(N, V, cosTheta, roughness);
vec3 F = fresnel_schlick(max(dot(H, V), 0.0), F0);
vec3 num = NDF * G * F;
float denom = 4.0 * max(dot(N, V), 0.0) * cosTheta;
vec3 spec = num / max(denom, 0.001);
vec3 kS = F;
vec3 kD = 1.0 - kS;
kD *= (1.0 - metalness);
vec3 Lo = (kD * albedo / M_PI + spec) * Li * cosTheta;
return Lo;
}
vec3 btdf_eval(vec3 N, vec3 L, vec3 albedo, vec3 Li) {
vec3 Lo = albedo * Li * max(dot(N, L), 0.0);
return Lo;
}
vec2 oct_encode(vec3 d) {
vec3 octant = sign(d);
// Compute l1-norm version of the direction vector
float sum = dot(d, octant);
vec3 octahedron = d / sum;
if (octahedron.z < 0.0) {
vec3 a = abs(octahedron);
octahedron.xy = octant.xy * (vec2(1.0) - a.yx);
}
return octahedron.xy * 0.5 + 0.5;
}
const mat2 octM0 = mat2(1.0, 0.0, 0.0, 1.0);
const mat2 octM1 = mat2(0.809017, 0.587785, -0.587785, 0.809017);
const mat2 octM2 = mat2(0.309017, 0.951057, -0.951057, 0.309017);
const mat2 octM3 = mat2(-0.309017, 0.951057, -0.951057, -0.309017);
float fbm(vec2 pos) {
float sum = 0.0;
sum += noise_2d(octM0 * pos);
sum += 0.5 * noise_2d(2.0 * octM1 * pos);
sum += 0.25 * noise_2d(4.0 * octM2 * pos);
sum += 0.125 * noise_2d(8.0 * octM3 * pos);
return sum;
}
vec2 fbm_sphere_sdf(vec3 center, float radius, vec3 pos) {
vec3 toP = pos - center;
radius = radius * mix(0.5, 1.0, uEnergy);
float d = length(toP);
vec2 uv = oct_encode(toP);
float amp = mix(0.1, 0.6, uEnergy);
float dd = fbm(uv * 15.0 + uTime * vec2(1.0, -0.4)) * amp;
return vec2(d + dd - radius,
mix(0.4, 1.0, float(d - (radius + 1.0 * amp) > 0.0)));
}
vec2 sample_scene(vec3 pos) {
return fbm_sphere_sdf(vec3(0.0, 0.0, -10.0), 2.0, pos);
}
const float sampleScale = 1.0 / sqrt(3.0) * 0.0005;
vec3 sample_normal(vec3 pos) {
#define NORMAL_SDF_SAMPLE_COUNT 4
vec3 normalSampleOffsets[NORMAL_SDF_SAMPLE_COUNT];
normalSampleOffsets[0] = vec3(1.0, -1.0, -1.0);
normalSampleOffsets[1] = vec3(-1.0, -1.0, 1.0);
normalSampleOffsets[2] = vec3(-1.0, 1.0, -1.0);
normalSampleOffsets[3] = vec3(1.0, 1.0, 1.0);
vec3 result = vec3(0.0);
for (int i = 0; i < NORMAL_SDF_SAMPLE_COUNT; ++i) {
result += normalSampleOffsets[i] * sampleScale *
sample_scene(pos + normalSampleOffsets[i]).x;
}
return normalize(result);
}
float raymarch(vec3 start, vec3 dir) {
float tMin = 8.0;
float tMax = 15.0;
float t = tMin;
float result = -1.0;
for (int i = 0; i < RAY_STEPS; ++i) {
if (t >= tMax)
break;
vec2 d = sample_scene(start + dir * t);
if (d.x < 0.0002) {
result = t;
break;
}
t += d.x * d.y;
}
return result;
}
void look_at(out mat3 cam, in vec3 eye, in vec3 center, in vec3 up) {
// Construct an ortho-normal basis for the camera
vec3 forward = normalize(center - eye);
vec3 right = cross(forward, up);
up = cross(right, forward);
cam = mat3(right, up, forward);
}
void sample_camera_ray(out vec3 origin, out vec3 direction, in mat3 cam,
vec3 eye, vec2 uv) {
uv *= 2.0;
uv -= 1.0;
uv.y *= -1.0;
float aspectRatio = uResolution.y / uResolution.x;
float vWidth = tan(uFov / 2.0);
float vHeight = vWidth * aspectRatio;
vec3 forward = cam * vec3(0.0, 0.0, 1.0);
vec3 rayDir = cam * vec3(uv.x * vWidth, uv.y * vHeight, 1.0);
origin = eye;
direction = normalize(rayDir);
}
vec3 sample_disk_light(out vec3 L, vec3 P, vec3 N, vec3 lightP, vec3 lightN,
float lightR, vec3 lightAtt, vec3 lightLumP) {
vec3 toL = closest_point_on_disc(lightP, lightN, lightR, P) - P;
L = normalize(toL);
toL *= lightAtt.x;
float illuminance = evalIlluminanceDisk(N, L, lightN, lightR, dot(toL, toL));
vec3 Li = lightLumP * illuminance;
return Li;
}
vec4 pixel_color(vec3 o, vec3 d, vec3 lightP, vec3 lightN, float lightR,
vec3 lightAtt, vec3 lightLumP) {
float t = raymarch(o, d);
vec4 result = vec4(0.0);
if (t >= 0.0) {
vec3 P = o + d * t;
vec3 N = sample_normal(P);
vec3 V = -d;
vec3 R = refract(-V, N, uIor);
float z = dot(vec3(0.0, 0.0, -1.0), P);
float zd = smoothstep(mix(0.0, 11.0, uAmbientLightDepthFactor), 14.0, z);
vec3 Lo = vec3(0.0);
vec3 L, Li;
vec3 S = fresnel_schlick(max(dot(N, V), 0.0), vec3(0.02));
Li =
sample_disk_light(L, P, R, lightP, lightN, lightR, lightAtt, lightLumP);
Lo += (1.0 - S) * brdf_eval(-N, L, normalize(L + R), R, uAlbedo, uRoughness,
uMetalness, Li);
Lo += zd * uAlbedo * uAmbientLight;
result = vec4(Lo, 1.0);
}
return result;
}
void main() {
vec2 uv = vec2(FlutterFragCoord().xy) / uResolution;
vec3 lightN = normalize(-uLightDir);
vec3 lightP = vec3(0.0, 0.0, -10.0) + uLightDir;
vec3 lightAtt = vec3(uLightQuadAtt, 0.0, 1.0);
vec3 eye = vec3(0.0, 0.0, 1.0);
vec3 center = vec3(0.0, 0.0, 0.0);
vec3 up = vec3(0.0, 1.0, 0.0);
mat3 cam;
look_at(cam, eye, center, up);
vec3 o, d;
sample_camera_ray(o, d, cam, eye, uv);
vec4 hdrColor =
abs(pixel_color(o, d, lightP, lightN, uLightR, lightAtt, uLightLumP));
vec3 ldrColor = vec3(1.0) - exp(min(-(hdrColor.rgb) * uExposure, 0.0));
oColor = vec4(ldrColor, hdrColor.a);
}
| codelabs/next-gen-ui/step_03_a/assets/shaders/orb_shader.frag/0 | {
"file_path": "codelabs/next-gen-ui/step_03_a/assets/shaders/orb_shader.frag",
"repo_id": "codelabs",
"token_count": 4116
} | 85 |
// Copyright 2023 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';
class TextStyles {
static const _font1 = TextStyle(fontFamily: 'Exo', color: Colors.white);
static TextStyle get h1 => _font1.copyWith(
fontSize: 75, letterSpacing: 35, fontWeight: FontWeight.w700);
static TextStyle get h2 => h1.copyWith(fontSize: 40, letterSpacing: 0);
static TextStyle get h3 =>
h1.copyWith(fontSize: 24, letterSpacing: 20, fontWeight: FontWeight.w400);
static TextStyle get body => _font1.copyWith(fontSize: 16);
static TextStyle get btn => _font1.copyWith(
fontSize: 16,
fontWeight: FontWeight.bold,
letterSpacing: 10,
);
}
abstract class AppColors {
static const orbColors = [
Color(0xFF71FDBF),
Color(0xFFCE33FF),
Color(0xFFFF5033),
];
static const emitColors = [
Color(0xFF96FF33),
Color(0xFF00FFFF),
Color(0xFFFF993E),
];
}
| codelabs/next-gen-ui/step_03_c/lib/styles.dart/0 | {
"file_path": "codelabs/next-gen-ui/step_03_c/lib/styles.dart",
"repo_id": "codelabs",
"token_count": 396
} | 86 |
// Copyright 2023 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:extra_alignments/extra_alignments.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:focusable_control_builder/focusable_control_builder.dart';
import 'package:gap/gap.dart';
import '../assets.dart';
import '../common/ui_scaler.dart';
import '../styles.dart';
class TitleScreenUi extends StatelessWidget {
const TitleScreenUi({
super.key,
required this.difficulty,
required this.onDifficultyPressed,
required this.onDifficultyFocused,
});
final int difficulty;
final void Function(int difficulty) onDifficultyPressed;
final void Function(int? difficulty) onDifficultyFocused;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 50),
child: Stack(
children: [
/// Title Text
const TopLeft(
child: UiScaler(
alignment: Alignment.topLeft,
child: _TitleText(),
),
),
/// Difficulty Btns
BottomLeft(
child: UiScaler(
alignment: Alignment.bottomLeft,
child: _DifficultyBtns(
difficulty: difficulty,
onDifficultyPressed: onDifficultyPressed,
onDifficultyFocused: onDifficultyFocused,
),
),
),
/// StartBtn
BottomRight(
child: UiScaler(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.only(bottom: 20, right: 40),
child: _StartBtn(onPressed: () {}),
),
),
),
],
),
);
}
}
class _TitleText extends StatelessWidget {
const _TitleText();
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Gap(20),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Transform.translate(
offset: Offset(-(TextStyles.h1.letterSpacing! * .5), 0),
child: Text('OUTPOST', style: TextStyles.h1),
),
Image.asset(AssetPaths.titleSelectedLeft, height: 65),
Text('57', style: TextStyles.h2),
Image.asset(AssetPaths.titleSelectedRight, height: 65),
],
).animate().fadeIn(delay: .8.seconds, duration: .7.seconds),
Text('INTO THE UNKNOWN', style: TextStyles.h3)
.animate()
.fadeIn(delay: 1.seconds, duration: .7.seconds),
],
);
}
}
class _DifficultyBtns extends StatelessWidget {
const _DifficultyBtns({
required this.difficulty,
required this.onDifficultyPressed,
required this.onDifficultyFocused,
});
final int difficulty;
final void Function(int difficulty) onDifficultyPressed;
final void Function(int? difficulty) onDifficultyFocused;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
_DifficultyBtn(
label: 'Casual',
selected: difficulty == 0,
onPressed: () => onDifficultyPressed(0),
onHover: (over) => onDifficultyFocused(over ? 0 : null),
),
_DifficultyBtn(
label: 'Normal',
selected: difficulty == 1,
onPressed: () => onDifficultyPressed(1),
onHover: (over) => onDifficultyFocused(over ? 1 : null),
),
_DifficultyBtn(
label: 'Hardcore',
selected: difficulty == 2,
onPressed: () => onDifficultyPressed(2),
onHover: (over) => onDifficultyFocused(over ? 2 : null),
),
const Gap(20),
],
);
}
}
class _DifficultyBtn extends StatelessWidget {
const _DifficultyBtn({
required this.selected,
required this.onPressed,
required this.onHover,
required this.label,
});
final String label;
final bool selected;
final VoidCallback onPressed;
final void Function(bool hasFocus) onHover;
@override
Widget build(BuildContext context) {
return FocusableControlBuilder(
onPressed: onPressed,
onHoverChanged: (_, state) => onHover.call(state.isHovered),
builder: (_, state) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
width: 250,
height: 60,
child: Stack(
children: [
/// Bg with fill and outline
Container(
decoration: BoxDecoration(
color: const Color(0xFF00D1FF).withOpacity(.1),
border: Border.all(color: Colors.white, width: 5),
),
),
if (state.isHovered || state.isFocused) ...[
Container(
decoration: BoxDecoration(
color: const Color(0xFF00D1FF).withOpacity(.1),
),
),
],
/// cross-hairs (selected state)
if (selected) ...[
CenterLeft(
child: Image.asset(AssetPaths.titleSelectedLeft),
),
CenterRight(
child: Image.asset(AssetPaths.titleSelectedRight),
),
],
/// Label
Center(
child: Text(label.toUpperCase(), style: TextStyles.btn),
),
],
),
),
);
},
);
}
}
class _StartBtn extends StatefulWidget {
const _StartBtn({required this.onPressed});
final VoidCallback onPressed;
@override
State<_StartBtn> createState() => _StartBtnState();
}
class _StartBtnState extends State<_StartBtn> {
AnimationController? _btnAnim;
bool _wasHovered = false;
@override
Widget build(BuildContext context) {
return FocusableControlBuilder(
cursor: SystemMouseCursors.click,
onPressed: widget.onPressed,
builder: (_, state) {
if ((state.isHovered || state.isFocused) &&
!_wasHovered &&
_btnAnim?.status != AnimationStatus.forward) {
_btnAnim?.forward(from: 0);
}
_wasHovered = (state.isHovered || state.isFocused);
return SizedBox(
width: 520,
height: 100,
child: Stack(
children: [
Positioned.fill(child: Image.asset(AssetPaths.titleStartBtn)),
if (state.isHovered || state.isFocused) ...[
Positioned.fill(
child: Image.asset(AssetPaths.titleStartBtnHover)),
],
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text('START MISSION',
style: TextStyles.btn
.copyWith(fontSize: 24, letterSpacing: 18)),
],
),
),
],
),
);
},
);
}
}
| codelabs/next-gen-ui/step_04_a/lib/title_screen/title_screen_ui.dart/0 | {
"file_path": "codelabs/next-gen-ui/step_04_a/lib/title_screen/title_screen_ui.dart",
"repo_id": "codelabs",
"token_count": 3643
} | 87 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/next-gen-ui/step_04_a/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/next-gen-ui/step_04_a/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 88 |
#import "GeneratedPluginRegistrant.h"
| codelabs/next-gen-ui/step_04_b/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/next-gen-ui/step_04_b/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 89 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/next-gen-ui/step_04_d/android/gradle.properties/0 | {
"file_path": "codelabs/next-gen-ui/step_04_d/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 90 |
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
window_size
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)
| codelabs/next-gen-ui/step_04_d/linux/flutter/generated_plugins.cmake/0 | {
"file_path": "codelabs/next-gen-ui/step_04_d/linux/flutter/generated_plugins.cmake",
"repo_id": "codelabs",
"token_count": 317
} | 91 |
// Copyright 2023 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';
import 'package:flutter/scheduler.dart';
class TickingBuilder extends StatefulWidget {
const TickingBuilder({super.key, required this.builder});
final Widget Function(BuildContext context, double time) builder;
@override
State<TickingBuilder> createState() => _TickingBuilderState();
}
class _TickingBuilderState extends State<TickingBuilder>
with SingleTickerProviderStateMixin {
late final Ticker _ticker;
double _time = 0.0;
@override
void initState() {
super.initState();
_ticker = createTicker(_handleTick)..start();
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
void _handleTick(Duration elapsed) {
setState(() => _time = elapsed.inMilliseconds.toDouble() / 1000.0);
}
@override
Widget build(BuildContext context) => widget.builder.call(context, _time);
}
| codelabs/next-gen-ui/step_04_e/lib/common/ticking_builder.dart/0 | {
"file_path": "codelabs/next-gen-ui/step_04_e/lib/common/ticking_builder.dart",
"repo_id": "codelabs",
"token_count": 335
} | 92 |
// Copyright 2023 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:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:provider/provider.dart';
import 'package:window_size/window_size.dart';
import 'assets.dart';
import 'title_screen/title_screen.dart';
void main() {
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
WidgetsFlutterBinding.ensureInitialized();
setWindowMinSize(const Size(800, 500));
}
Animate.restartOnHotReload = true;
runApp(
FutureProvider<FragmentPrograms?>(
create: (context) => loadFragmentPrograms(),
initialData: null,
child: const NextGenApp(),
),
);
}
class NextGenApp extends StatelessWidget {
const NextGenApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
themeMode: ThemeMode.dark,
darkTheme: ThemeData(brightness: Brightness.dark),
home: const TitleScreen(),
);
}
}
| codelabs/next-gen-ui/step_05_a/lib/main.dart/0 | {
"file_path": "codelabs/next-gen-ui/step_05_a/lib/main.dart",
"repo_id": "codelabs",
"token_count": 409
} | 93 |
# Copyright 2020 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.
name: testing_app
description: "App behind Flutter testing codelab."
publish_to: 'none'
version: 0.1.0
environment:
sdk: '>=3.3.0-279.2.beta <4.0.0'
dependencies:
flutter:
sdk: flutter
go_router: ^13.1.0
provider: ^6.1.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
flutter_driver:
sdk: flutter
integration_test:
sdk: flutter
test: ^1.24.9
flutter:
uses-material-design: true
| codelabs/testing_codelab/step_05/pubspec.yaml/0 | {
"file_path": "codelabs/testing_codelab/step_05/pubspec.yaml",
"repo_id": "codelabs",
"token_count": 242
} | 94 |
// Copyright 2020 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';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:testing_app/main.dart';
void main() {
group('Testing App Performance', () {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;
testWidgets('Scrolling test', (tester) async {
await tester.pumpWidget(const TestingApp());
final listFinder = find.byType(ListView);
await binding.traceAction(() async {
await tester.fling(listFinder, const Offset(0, -500), 10000);
await tester.pumpAndSettle();
await tester.fling(listFinder, const Offset(0, 500), 10000);
await tester.pumpAndSettle();
}, reportKey: 'scrolling_summary');
});
});
}
| codelabs/testing_codelab/step_08/integration_test/perf_test.dart/0 | {
"file_path": "codelabs/testing_codelab/step_08/integration_test/perf_test.dart",
"repo_id": "codelabs",
"token_count": 358
} | 95 |
#include "Generated.xcconfig"
| codelabs/tfagents-flutter/step2/frontend/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/step2/frontend/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 96 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/tfagents-flutter/step2/frontend/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/step2/frontend/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 97 |
include: ../../../analysis_options.yaml
analyzer:
errors:
unused_import: ignore
unused_field: ignore
unused_local_variable: ignore
linter:
rules:
- use_super_parameters | codelabs/tfagents-flutter/step4/frontend/analysis_options.yaml/0 | {
"file_path": "codelabs/tfagents-flutter/step4/frontend/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 70
} | 98 |
# Copyright 2022 The TensorFlow 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.
"""TF Agents training code for the Plane Strike board game."""
from typing import Sequence
from absl import app
import reverb
import tensorflow as tf
import planestrike_py_environment
import tensorflow_probability as tfp
import tf_agents as tfa
from tf_agents.agents.reinforce import reinforce_agent
from tf_agents.drivers import py_driver
from tf_agents.environments import tf_py_environment
from tf_agents.policies import policy_saver
from tf_agents.policies import py_tf_eager_policy
from tf_agents.replay_buffers import reverb_replay_buffer
from tf_agents.replay_buffers import reverb_utils
from tf_agents.specs import tensor_spec
from tf_agents.utils import common
BOARD_SIZE = 8
ITERATIONS = 250000
COLLECT_EPISODES_PER_ITERATION = 1
REPLAY_BUFFER_CAPACITY = 2000
REPLAY_BUFFER_TABLE_NAME = "uniform_table"
DISCOUNT = 0.5
FC_LAYER_PARAMS = 100
LEARNING_RATE = 1e-3
NUM_EVAL_EPISODES = 20
EVAL_INTERVAL = 500
LOGDIR = "./tf_agents_log"
MODELDIR = "./"
POLICYDIR = "./policy_model/123"
def compute_avg_return_and_steps(environment, policy, num_episodes=10):
"""Compute average return and # of steps."""
total_return = 0.0
total_steps = 0.0
for _ in range(num_episodes):
time_step = environment.reset()
episode_return = 0.0
episode_steps = 0.0
while not time_step.is_last():
action_step = policy.action(time_step)
time_step = environment.step(action_step.action)
episode_return += time_step.reward
episode_steps += 1
total_return += episode_return
total_steps += episode_steps
average_return = total_return / num_episodes
average_episode_steps = total_steps / num_episodes
return average_return.numpy()[0], average_episode_steps
def collect_episode(environment, policy, num_episodes, replay_buffer_observer):
"""Collect game episode trajectories."""
initial_time_step = environment.reset()
driver = py_driver.PyDriver(
environment,
py_tf_eager_policy.PyTFEagerPolicy(policy, use_tf_function=True),
[replay_buffer_observer],
max_episodes=num_episodes,
)
initial_time_step = environment.reset()
driver.run(initial_time_step)
def train_agent(iterations, modeldir, logdir, policydir):
"""Train and convert the model using TF Agents."""
train_py_env = planestrike_py_environment.PlaneStrikePyEnvironment(
board_size=BOARD_SIZE, discount=DISCOUNT, max_steps=BOARD_SIZE**2
)
eval_py_env = planestrike_py_environment.PlaneStrikePyEnvironment(
board_size=BOARD_SIZE, discount=DISCOUNT, max_steps=BOARD_SIZE**2
)
train_env = tf_py_environment.TFPyEnvironment(train_py_env)
eval_env = tf_py_environment.TFPyEnvironment(eval_py_env)
# Alternatively you could use ActorDistributionNetwork as actor_net
actor_net = tfa.networks.Sequential(
[
tfa.keras_layers.InnerReshape([BOARD_SIZE, BOARD_SIZE], [BOARD_SIZE**2]),
tf.keras.layers.Dense(FC_LAYER_PARAMS, activation="relu"),
tf.keras.layers.Dense(BOARD_SIZE**2),
tf.keras.layers.Lambda(lambda t: tfp.distributions.Categorical(logits=t)),
],
input_spec=train_py_env.observation_spec(),
)
optimizer = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE)
train_step_counter = tf.Variable(0)
tf_agent = reinforce_agent.ReinforceAgent(
train_env.time_step_spec(),
train_env.action_spec(),
actor_network=actor_net,
optimizer=optimizer,
normalize_returns=True,
train_step_counter=train_step_counter,
)
tf_agent.initialize()
eval_policy = tf_agent.policy
collect_policy = tf_agent.collect_policy
tf_policy_saver = policy_saver.PolicySaver(collect_policy)
# Use reverb as replay buffer
replay_buffer_signature = tensor_spec.from_spec(tf_agent.collect_data_spec)
replay_buffer_signature = tensor_spec.add_outer_dim(replay_buffer_signature)
table = reverb.Table(
REPLAY_BUFFER_TABLE_NAME,
max_size=REPLAY_BUFFER_CAPACITY,
sampler=reverb.selectors.Uniform(),
remover=reverb.selectors.Fifo(),
rate_limiter=reverb.rate_limiters.MinSize(1),
signature=replay_buffer_signature,
) # specify signature here for validation at insertion time
reverb_server = reverb.Server([table])
replay_buffer = reverb_replay_buffer.ReverbReplayBuffer(
tf_agent.collect_data_spec,
sequence_length=None,
table_name=REPLAY_BUFFER_TABLE_NAME,
local_server=reverb_server,
)
replay_buffer_observer = reverb_utils.ReverbAddEpisodeObserver(
replay_buffer.py_client, REPLAY_BUFFER_TABLE_NAME, REPLAY_BUFFER_CAPACITY
)
# Optimize by wrapping some of the code in a graph using TF function.
tf_agent.train = common.function(tf_agent.train)
# Evaluate the agent's policy once before training.
avg_return = compute_avg_return_and_steps(
eval_env, tf_agent.policy, NUM_EVAL_EPISODES
)
summary_writer = tf.summary.create_file_writer(logdir)
for i in range(iterations):
# Collect a few episodes using collect_policy and save to the replay buffer.
collect_episode(
train_py_env,
collect_policy,
COLLECT_EPISODES_PER_ITERATION,
replay_buffer_observer,
)
# Use data from the buffer and update the agent's network.
iterator = iter(replay_buffer.as_dataset(sample_batch_size=1))
trajectories, _ = next(iterator)
tf_agent.train(experience=trajectories)
replay_buffer.clear()
logger = tf.get_logger()
if i % EVAL_INTERVAL == 0:
avg_return, avg_episode_length = compute_avg_return_and_steps(
eval_env, eval_policy, NUM_EVAL_EPISODES
)
with summary_writer.as_default():
tf.summary.scalar("Average return", avg_return, step=i)
tf.summary.scalar("Average episode length", avg_episode_length, step=i)
summary_writer.flush()
logger.info(
"iteration = {0}: Average Return = {1}, Average Episode Length = {2}".format(
i, avg_return, avg_episode_length
)
)
summary_writer.close()
tf_policy_saver.save(policydir)
def main(argv: Sequence[str]) -> None:
if len(argv) > 1:
raise app.UsageError("Too many command-line arguments.")
train_agent(ITERATIONS, MODELDIR, LOGDIR, POLICYDIR)
if __name__ == "__main__":
app.run(main)
| codelabs/tfagents-flutter/step5/backend/training.py/0 | {
"file_path": "codelabs/tfagents-flutter/step5/backend/training.py",
"repo_id": "codelabs",
"token_count": 2917
} | 99 |
import 'dart:convert';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:http/http.dart' as http;
class Inputs {
final List<double> _boardState;
Inputs(this._boardState);
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['0/discount'] = [0.0];
data['0/observation'] = [_boardState];
data['0/reward'] = [0.0];
data['0/step_type'] = [0];
return data;
}
}
class TFAgentsAgent {
TFAgentsAgent();
Future<int> predict(List<List<double>> boardState) async {
String server = '';
if (!kIsWeb && Platform.isAndroid) {
// For Android emulator
server = '10.0.2.2';
} else {
// For iOS emulator, desktop and web platforms
server = '127.0.0.1';
}
var flattenedBoardState = boardState.expand((i) => i).toList();
final response = await http.post(
Uri.parse('http://$server:8501/v1/models/policy_model:predict'),
body: jsonEncode(<String, dynamic>{
'signature_name': 'action',
'instances': [Inputs(flattenedBoardState)]
}),
);
if (response.statusCode == 200) {
var output = List<int>.from(
jsonDecode(response.body)['predictions'] as List<dynamic>);
return output[0];
} else {
throw Exception('Error response');
}
}
}
| codelabs/tfagents-flutter/step6/frontend/lib/game_agent.dart/0 | {
"file_path": "codelabs/tfagents-flutter/step6/frontend/lib/game_agent.dart",
"repo_id": "codelabs",
"token_count": 559
} | 100 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/tfagents-flutter/step6/frontend/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/step6/frontend/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 101 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| codelabs/tfrs-flutter/finished/frontend/android/gradle.properties/0 | {
"file_path": "codelabs/tfrs-flutter/finished/frontend/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 31
} | 102 |
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
void main() => runApp(const RecommenderDemo());
class RecommenderDemo extends StatefulWidget {
const RecommenderDemo({super.key});
@override
State<RecommenderDemo> createState() => _RecommenderDemoState();
}
class _RecommenderDemoState extends State<RecommenderDemo> {
late List<String> _movieList;
final TextEditingController _userIDController = TextEditingController();
late String _server;
late Future<List<String>> _futureRecommendations;
@override
void initState() {
super.initState();
_futureRecommendations = Future<List<String>>.value([]);
}
Future<List<String>> recommend() async {
if (!kIsWeb && Platform.isAndroid) {
// For Android emulator
_server = '10.0.2.2';
} else {
// For iOS emulator, desktop and web platforms
_server = '127.0.0.1';
}
//TODO: add code to send request to the recommendation engine backend
return [];
}
@override
Widget build(BuildContext context) {
const title = 'Flutter Movie Recommendation Demo';
return MaterialApp(
title: title,
theme: ThemeData.light(useMaterial3: true),
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: Center(
child: Container(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: TextField(
controller: _userIDController,
decoration: const InputDecoration(
border: UnderlineInputBorder(),
hintText: 'Enter a user ID here'),
)),
Container(
margin: const EdgeInsets.only(left: 10.0),
child: FilledButton(
style: FilledButton.styleFrom(
textStyle: const TextStyle(fontSize: 15),
),
onPressed: () {
setState(() {
_futureRecommendations = recommend();
});
},
child: const Text('Recommend'))),
]),
FutureBuilder<List<String>>(
future: _futureRecommendations,
builder: (context, snapshot) {
if (snapshot.hasData) {
_movieList = snapshot.data!;
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: _movieList.length,
itemBuilder: (context, index) {
return ListTile(
leading: _movieList.isEmpty
? null
: const FlutterLogo(),
title: Text(_movieList[index]),
);
},
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
]),
),
),
),
);
}
}
| codelabs/tfrs-flutter/step0/frontend/lib/main.dart/0 | {
"file_path": "codelabs/tfrs-flutter/step0/frontend/lib/main.dart",
"repo_id": "codelabs",
"token_count": 2208
} | 103 |
# Fullstack demo of a recommendation engine
This folder contains the code for [TensorFlow Recommenders](https://www.tensorflow.org/recommenders) + Flutter codelab. | codelabs/tfrs-flutter/step1/README.md/0 | {
"file_path": "codelabs/tfrs-flutter/step1/README.md",
"repo_id": "codelabs",
"token_count": 43
} | 104 |
package com.example.recommend_products
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| codelabs/tfrs-flutter/step3/frontend/android/app/src/main/kotlin/com/example/recommend_products/MainActivity.kt/0 | {
"file_path": "codelabs/tfrs-flutter/step3/frontend/android/app/src/main/kotlin/com/example/recommend_products/MainActivity.kt",
"repo_id": "codelabs",
"token_count": 39
} | 105 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/tfrs-flutter/step3/frontend/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/tfrs-flutter/step3/frontend/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 106 |
#include "Generated.xcconfig"
| codelabs/tfrs-flutter/step5/frontend/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/tfrs-flutter/step5/frontend/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 107 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/tfserving-flutter/codelab2/finished/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/finished/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 108 |
///
// Generated code. Do not modify.
// source: google/protobuf/wrappers.proto
//
// @dart = 2.12
// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/google/protobuf/wrappers.pbenum.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/google/protobuf/wrappers.pbenum.dart",
"repo_id": "codelabs",
"token_count": 114
} | 109 |
///
// Generated code. Do not modify.
// source: tensorflow/core/framework/tensor_shape.proto
//
// @dart = 2.12
// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields
import 'dart:core' as $core;
import 'package:fixnum/fixnum.dart' as $fixnum;
import 'package:protobuf/protobuf.dart' as $pb;
class TensorShapeProto_Dim extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'TensorShapeProto.Dim',
package: const $pb.PackageName(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'tensorflow'),
createEmptyInstance: create)
..aInt64(
1,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'size')
..aOS(
2,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'name')
..hasRequiredFields = false;
TensorShapeProto_Dim._() : super();
factory TensorShapeProto_Dim({
$fixnum.Int64? size,
$core.String? name,
}) {
final _result = create();
if (size != null) {
_result.size = size;
}
if (name != null) {
_result.name = name;
}
return _result;
}
factory TensorShapeProto_Dim.fromBuffer($core.List<$core.int> i,
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromBuffer(i, r);
factory TensorShapeProto_Dim.fromJson($core.String i,
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(i, r);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
TensorShapeProto_Dim clone() =>
TensorShapeProto_Dim()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
TensorShapeProto_Dim copyWith(void Function(TensorShapeProto_Dim) updates) =>
super.copyWith((message) => updates(message as TensorShapeProto_Dim))
as TensorShapeProto_Dim; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static TensorShapeProto_Dim create() => TensorShapeProto_Dim._();
TensorShapeProto_Dim createEmptyInstance() => create();
static $pb.PbList<TensorShapeProto_Dim> createRepeated() =>
$pb.PbList<TensorShapeProto_Dim>();
@$core.pragma('dart2js:noInline')
static TensorShapeProto_Dim getDefault() => _defaultInstance ??=
$pb.GeneratedMessage.$_defaultFor<TensorShapeProto_Dim>(create);
static TensorShapeProto_Dim? _defaultInstance;
@$pb.TagNumber(1)
$fixnum.Int64 get size => $_getI64(0);
@$pb.TagNumber(1)
set size($fixnum.Int64 v) {
$_setInt64(0, v);
}
@$pb.TagNumber(1)
$core.bool hasSize() => $_has(0);
@$pb.TagNumber(1)
void clearSize() => clearField(1);
@$pb.TagNumber(2)
$core.String get name => $_getSZ(1);
@$pb.TagNumber(2)
set name($core.String v) {
$_setString(1, v);
}
@$pb.TagNumber(2)
$core.bool hasName() => $_has(1);
@$pb.TagNumber(2)
void clearName() => clearField(2);
}
class TensorShapeProto extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'TensorShapeProto',
package: const $pb.PackageName(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'tensorflow'),
createEmptyInstance: create)
..pc<TensorShapeProto_Dim>(
2,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'dim',
$pb.PbFieldType.PM,
subBuilder: TensorShapeProto_Dim.create)
..aOB(
3,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'unknownRank')
..hasRequiredFields = false;
TensorShapeProto._() : super();
factory TensorShapeProto({
$core.Iterable<TensorShapeProto_Dim>? dim,
$core.bool? unknownRank,
}) {
final _result = create();
if (dim != null) {
_result.dim.addAll(dim);
}
if (unknownRank != null) {
_result.unknownRank = unknownRank;
}
return _result;
}
factory TensorShapeProto.fromBuffer($core.List<$core.int> i,
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromBuffer(i, r);
factory TensorShapeProto.fromJson($core.String i,
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromJson(i, r);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
TensorShapeProto clone() => TensorShapeProto()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
TensorShapeProto copyWith(void Function(TensorShapeProto) updates) =>
super.copyWith((message) => updates(message as TensorShapeProto))
as TensorShapeProto; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static TensorShapeProto create() => TensorShapeProto._();
TensorShapeProto createEmptyInstance() => create();
static $pb.PbList<TensorShapeProto> createRepeated() =>
$pb.PbList<TensorShapeProto>();
@$core.pragma('dart2js:noInline')
static TensorShapeProto getDefault() => _defaultInstance ??=
$pb.GeneratedMessage.$_defaultFor<TensorShapeProto>(create);
static TensorShapeProto? _defaultInstance;
@$pb.TagNumber(2)
$core.List<TensorShapeProto_Dim> get dim => $_getList(0);
@$pb.TagNumber(3)
$core.bool get unknownRank => $_getBF(1);
@$pb.TagNumber(3)
set unknownRank($core.bool v) {
$_setBool(1, v);
}
@$pb.TagNumber(3)
$core.bool hasUnknownRank() => $_has(1);
@$pb.TagNumber(3)
void clearUnknownRank() => clearField(3);
}
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/tensor_shape.pb.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/tensor_shape.pb.dart",
"repo_id": "codelabs",
"token_count": 2679
} | 110 |
///
// Generated code. Do not modify.
// source: tensorflow/core/protobuf/saved_object_graph.proto
//
// @dart = 2.12
// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields
// ignore_for_file: UNDEFINED_SHOWN_NAME
import 'dart:core' as $core;
import 'package:protobuf/protobuf.dart' as $pb;
class FunctionSpec_JitCompile extends $pb.ProtobufEnum {
static const FunctionSpec_JitCompile DEFAULT = FunctionSpec_JitCompile._(
0,
const $core.bool.fromEnvironment('protobuf.omit_enum_names')
? ''
: 'DEFAULT');
static const FunctionSpec_JitCompile ON = FunctionSpec_JitCompile._(1,
const $core.bool.fromEnvironment('protobuf.omit_enum_names') ? '' : 'ON');
static const FunctionSpec_JitCompile OFF = FunctionSpec_JitCompile._(
2,
const $core.bool.fromEnvironment('protobuf.omit_enum_names')
? ''
: 'OFF');
static const $core.List<FunctionSpec_JitCompile> values =
<FunctionSpec_JitCompile>[
DEFAULT,
ON,
OFF,
];
static final $core.Map<$core.int, FunctionSpec_JitCompile> _byValue =
$pb.ProtobufEnum.initByValue(values);
static FunctionSpec_JitCompile? valueOf($core.int value) => _byValue[value];
const FunctionSpec_JitCompile._($core.int v, $core.String n) : super(v, n);
}
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/protobuf/saved_object_graph.pbenum.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/protobuf/saved_object_graph.pbenum.dart",
"repo_id": "codelabs",
"token_count": 575
} | 111 |
///
// Generated code. Do not modify.
// source: tensorflow_serving/apis/get_model_metadata.proto
//
// @dart = 2.12
// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package
import 'dart:core' as $core;
import 'dart:convert' as $convert;
import 'dart:typed_data' as $typed_data;
@$core.Deprecated('Use signatureDefMapDescriptor instead')
const SignatureDefMap$json = const {
'1': 'SignatureDefMap',
'2': const [
const {
'1': 'signature_def',
'3': 1,
'4': 3,
'5': 11,
'6': '.tensorflow.serving.SignatureDefMap.SignatureDefEntry',
'10': 'signatureDef'
},
],
'3': const [SignatureDefMap_SignatureDefEntry$json],
};
@$core.Deprecated('Use signatureDefMapDescriptor instead')
const SignatureDefMap_SignatureDefEntry$json = const {
'1': 'SignatureDefEntry',
'2': const [
const {'1': 'key', '3': 1, '4': 1, '5': 9, '10': 'key'},
const {
'1': 'value',
'3': 2,
'4': 1,
'5': 11,
'6': '.tensorflow.SignatureDef',
'10': 'value'
},
],
'7': const {'7': true},
};
/// Descriptor for `SignatureDefMap`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List signatureDefMapDescriptor = $convert.base64Decode(
'Cg9TaWduYXR1cmVEZWZNYXASWgoNc2lnbmF0dXJlX2RlZhgBIAMoCzI1LnRlbnNvcmZsb3cuc2VydmluZy5TaWduYXR1cmVEZWZNYXAuU2lnbmF0dXJlRGVmRW50cnlSDHNpZ25hdHVyZURlZhpZChFTaWduYXR1cmVEZWZFbnRyeRIQCgNrZXkYASABKAlSA2tleRIuCgV2YWx1ZRgCIAEoCzIYLnRlbnNvcmZsb3cuU2lnbmF0dXJlRGVmUgV2YWx1ZToCOAE=');
@$core.Deprecated('Use getModelMetadataRequestDescriptor instead')
const GetModelMetadataRequest$json = const {
'1': 'GetModelMetadataRequest',
'2': const [
const {
'1': 'model_spec',
'3': 1,
'4': 1,
'5': 11,
'6': '.tensorflow.serving.ModelSpec',
'10': 'modelSpec'
},
const {
'1': 'metadata_field',
'3': 2,
'4': 3,
'5': 9,
'10': 'metadataField'
},
],
};
/// Descriptor for `GetModelMetadataRequest`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List getModelMetadataRequestDescriptor =
$convert.base64Decode(
'ChdHZXRNb2RlbE1ldGFkYXRhUmVxdWVzdBI8Cgptb2RlbF9zcGVjGAEgASgLMh0udGVuc29yZmxvdy5zZXJ2aW5nLk1vZGVsU3BlY1IJbW9kZWxTcGVjEiUKDm1ldGFkYXRhX2ZpZWxkGAIgAygJUg1tZXRhZGF0YUZpZWxk');
@$core.Deprecated('Use getModelMetadataResponseDescriptor instead')
const GetModelMetadataResponse$json = const {
'1': 'GetModelMetadataResponse',
'2': const [
const {
'1': 'model_spec',
'3': 1,
'4': 1,
'5': 11,
'6': '.tensorflow.serving.ModelSpec',
'10': 'modelSpec'
},
const {
'1': 'metadata',
'3': 2,
'4': 3,
'5': 11,
'6': '.tensorflow.serving.GetModelMetadataResponse.MetadataEntry',
'10': 'metadata'
},
],
'3': const [GetModelMetadataResponse_MetadataEntry$json],
};
@$core.Deprecated('Use getModelMetadataResponseDescriptor instead')
const GetModelMetadataResponse_MetadataEntry$json = const {
'1': 'MetadataEntry',
'2': const [
const {'1': 'key', '3': 1, '4': 1, '5': 9, '10': 'key'},
const {
'1': 'value',
'3': 2,
'4': 1,
'5': 11,
'6': '.google.protobuf.Any',
'10': 'value'
},
],
'7': const {'7': true},
};
/// Descriptor for `GetModelMetadataResponse`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List getModelMetadataResponseDescriptor =
$convert.base64Decode(
'ChhHZXRNb2RlbE1ldGFkYXRhUmVzcG9uc2USPAoKbW9kZWxfc3BlYxgBIAEoCzIdLnRlbnNvcmZsb3cuc2VydmluZy5Nb2RlbFNwZWNSCW1vZGVsU3BlYxJWCghtZXRhZGF0YRgCIAMoCzI6LnRlbnNvcmZsb3cuc2VydmluZy5HZXRNb2RlbE1ldGFkYXRhUmVzcG9uc2UuTWV0YWRhdGFFbnRyeVIIbWV0YWRhdGEaUQoNTWV0YWRhdGFFbnRyeRIQCgNrZXkYASABKAlSA2tleRIqCgV2YWx1ZRgCIAEoCzIULmdvb2dsZS5wcm90b2J1Zi5BbnlSBXZhbHVlOgI4AQ==');
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/get_model_metadata.pbjson.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/get_model_metadata.pbjson.dart",
"repo_id": "codelabs",
"token_count": 2013
} | 112 |
///
// Generated code. Do not modify.
// source: tensorflow_serving/apis/prediction_service.proto
//
// @dart = 2.12
// ignore_for_file: annotate_overrides,camel_case_types,unnecessary_const,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type,unnecessary_this,prefer_final_fields,deprecated_member_use_from_same_package
import 'dart:core' as $core;
import 'dart:convert' as $convert;
import 'dart:typed_data' as $typed_data;
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/prediction_service.pbjson.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/prediction_service.pbjson.dart",
"repo_id": "codelabs",
"token_count": 177
} | 113 |
// Protocol buffer representing the shape of tensors.
syntax = "proto3";
option cc_enable_arenas = true;
option java_outer_classname = "TensorShapeProtos";
option java_multiple_files = true;
option java_package = "org.tensorflow.framework";
option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/tensor_shape_go_proto";
package tensorflow;
// Dimensions of a tensor.
message TensorShapeProto {
// One dimension of the tensor.
message Dim {
// Size of the tensor in that dimension.
// This value must be >= -1, but values of -1 are reserved for "unknown"
// shapes (values of -1 mean "unknown" dimension). Certain wrappers
// that work with TensorShapeProto may fail at runtime when deserializing
// a TensorShapeProto containing a dim value of -1.
int64 size = 1;
// Optional name of the tensor dimension.
string name = 2;
};
// Dimensions of the tensor, such as {"input", 30}, {"output", 40}
// for a 30 x 40 2D tensor. If an entry has size -1, this
// corresponds to a dimension of unknown size. The names are
// optional.
//
// The order of entries in "dim" matters: It indicates the layout of the
// values in the tensor in-memory representation.
//
// The first entry in "dim" is the outermost dimension used to layout the
// values, the last entry is the innermost dimension. This matches the
// in-memory layout of RowMajor Eigen tensors.
//
// If "dim.size()" > 0, "unknown_rank" must be false.
repeated Dim dim = 2;
// If true, the number of dimensions in the shape is unknown.
//
// If true, "dim.size()" must be 0.
bool unknown_rank = 3;
};
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow/core/framework/tensor_shape.proto/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow/core/framework/tensor_shape.proto",
"repo_id": "codelabs",
"token_count": 517
} | 114 |
syntax = "proto3";
option cc_enable_arenas = true;
import "tensorflow_serving/apis/input.proto";
import "tensorflow_serving/apis/model.proto";
package tensorflow.serving;
// Regression result for a single item (tensorflow.Example).
message Regression {
float value = 1;
}
// Contains one result per input example, in the same order as the input in
// RegressionRequest.
message RegressionResult {
repeated Regression regressions = 1;
}
// RPC interfaces.
message RegressionRequest {
// Model Specification. If version is not specified, will use the latest
// (numerical) version.
ModelSpec model_spec = 1;
// Input data.
tensorflow.serving.Input input = 2;
}
message RegressionResponse {
// Effective Model Specification used for regression.
ModelSpec model_spec = 2;
RegressionResult result = 1;
}
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow_serving/apis/regression.proto/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow_serving/apis/regression.proto",
"repo_id": "codelabs",
"token_count": 248
} | 115 |
[
"test/data/exports/17L9jk2dhTFrdEqyLb6Wxhq0NeRrtzpQLLJv09qROsA8.json",
"test/data/exports/1CdlksSvxBE2XRBVZtOKpfMUO68OLJDLdQc7mxN_zABg.json",
"test/data/exports/1EQtDsZv6vkvgreuOrF0KMo6kiKJ-534DShEFGankv20.json",
"test/data/exports/1MfCrv1w6aK7SLq9gmjJwXCJFQ-AX9NWJit2gq-v2Xx8.json",
"test/data/exports/1NJq1PfV9mB2avhoM2l12DSQ8p2x6s_epXcLwCcZwpcg.json",
"test/data/exports/1Y099kkeEUvi3FRbE6a0pjZkkBzMHmraX3Q33zCC5uJM.json",
"test/data/exports/1ihOxu-DK3SBrUYyppRtzKvfwceSIzk4ZWzP9F6nRtnw.json",
"test/data/exports/1kwYB2RE1EXYMOt7F5fm-0nrY6BA1AyWsBXz2vlfTfxA.json"
] | codelabs/tooling/claat_export_images/test/data/data.json/0 | {
"file_path": "codelabs/tooling/claat_export_images/test/data/data.json",
"repo_id": "codelabs",
"token_count": 398
} | 116 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'blueprint.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Blueprint _$BlueprintFromJson(Map json) => $checkedCreate(
'Blueprint',
json,
($checkedConvert) {
$checkKeys(
json,
allowedKeys: const ['name', 'steps'],
requiredKeys: const ['name', 'steps'],
);
final val = Blueprint(
name: $checkedConvert('name', (v) => v as String),
steps: $checkedConvert(
'steps',
(v) => (v as List<dynamic>)
.map((e) => BlueprintStep.fromJson(e as Map))
.toList()),
);
return val;
},
);
Map<String, dynamic> _$BlueprintToJson(Blueprint instance) => <String, dynamic>{
'name': instance.name,
'steps': instance.steps,
};
BlueprintStep _$BlueprintStepFromJson(Map json) => $checkedCreate(
'BlueprintStep',
json,
($checkedConvert) {
$checkKeys(
json,
allowedKeys: const [
'name',
'steps',
'path',
'base64-contents',
'patch',
'patch-u',
'patch-c',
'replace-contents',
'platforms',
'dart',
'flutter',
'git',
'pod',
'rm',
'mkdir',
'mkdirs',
'rmdir',
'rmdirs',
'copydir',
'copy',
'rename',
'retrieve-url',
'tar',
'7z',
'strip-lines-containing',
'stop',
'xcode-add-file',
'xcode-project-path'
],
requiredKeys: const ['name'],
);
final val = BlueprintStep(
name: $checkedConvert('name', (v) => v as String),
steps: $checkedConvert(
'steps',
(v) =>
(v as List<dynamic>?)
?.map((e) => BlueprintStep.fromJson(e as Map))
.toList() ??
const []),
base64Contents:
$checkedConvert('base64-contents', (v) => v as String?),
patch: $checkedConvert('patch', (v) => v as String?),
patchU: $checkedConvert('patch-u', (v) => v as String?),
patchC: $checkedConvert('patch-c', (v) => v as String?),
path: $checkedConvert('path', (v) => v as String?),
replaceContents:
$checkedConvert('replace-contents', (v) => v as String?),
mkdir: $checkedConvert('mkdir', (v) => v as String?),
mkdirs: $checkedConvert(
'mkdirs',
(v) =>
(v as List<dynamic>?)?.map((e) => e as String).toList() ??
const []),
rmdir: $checkedConvert('rmdir', (v) => v as String?),
rmdirs: $checkedConvert(
'rmdirs',
(v) =>
(v as List<dynamic>?)?.map((e) => e as String).toList() ??
const []),
copydir: $checkedConvert(
'copydir', (v) => v == null ? null : FromTo.fromJson(v as Map)),
copy: $checkedConvert(
'copy', (v) => v == null ? null : FromTo.fromJson(v as Map)),
rename: $checkedConvert(
'rename', (v) => v == null ? null : FromTo.fromJson(v as Map)),
platforms: $checkedConvert('platforms',
(v) => (v as List<dynamic>?)?.map((e) => e as String).toList()),
dart: $checkedConvert('dart', (v) => v as String?),
flutter: $checkedConvert('flutter', (v) => v as String?),
git: $checkedConvert('git', (v) => v as String?),
rm: $checkedConvert('rm', (v) => v as String?),
pod: $checkedConvert('pod', (v) => v as String?),
retrieveUrl: $checkedConvert('retrieve-url', (v) => v as String?),
tar: $checkedConvert('tar', (v) => v as String?),
sevenZip: $checkedConvert('7z', (v) => v as String?),
stripLinesContaining:
$checkedConvert('strip-lines-containing', (v) => v as String?),
stop: $checkedConvert('stop', (v) => v as bool?),
xcodeAddFile: $checkedConvert('xcode-add-file', (v) => v as String?),
xcodeProjectPath:
$checkedConvert('xcode-project-path', (v) => v as String?),
);
return val;
},
fieldKeyMap: const {
'base64Contents': 'base64-contents',
'patchU': 'patch-u',
'patchC': 'patch-c',
'replaceContents': 'replace-contents',
'retrieveUrl': 'retrieve-url',
'sevenZip': '7z',
'stripLinesContaining': 'strip-lines-containing',
'xcodeAddFile': 'xcode-add-file',
'xcodeProjectPath': 'xcode-project-path'
},
);
Map<String, dynamic> _$BlueprintStepToJson(BlueprintStep instance) =>
<String, dynamic>{
'name': instance.name,
'steps': instance.steps,
'path': instance.path,
'base64-contents': instance.base64Contents,
'patch': instance.patch,
'patch-u': instance.patchU,
'patch-c': instance.patchC,
'replace-contents': instance.replaceContents,
'platforms': instance.platforms,
'dart': instance.dart,
'flutter': instance.flutter,
'git': instance.git,
'pod': instance.pod,
'rm': instance.rm,
'mkdir': instance.mkdir,
'mkdirs': instance.mkdirs,
'rmdir': instance.rmdir,
'rmdirs': instance.rmdirs,
'copydir': instance.copydir,
'copy': instance.copy,
'rename': instance.rename,
'retrieve-url': instance.retrieveUrl,
'tar': instance.tar,
'7z': instance.sevenZip,
'strip-lines-containing': instance.stripLinesContaining,
'stop': instance.stop,
'xcode-add-file': instance.xcodeAddFile,
'xcode-project-path': instance.xcodeProjectPath,
};
FromTo _$FromToFromJson(Map json) => $checkedCreate(
'FromTo',
json,
($checkedConvert) {
$checkKeys(
json,
allowedKeys: const ['from', 'to'],
);
final val = FromTo(
from: $checkedConvert('from', (v) => v as String),
to: $checkedConvert('to', (v) => v as String),
);
return val;
},
);
Map<String, dynamic> _$FromToToJson(FromTo instance) => <String, dynamic>{
'from': instance.from,
'to': instance.to,
};
| codelabs/tooling/codelab_rebuild/lib/src/blueprint.g.dart/0 | {
"file_path": "codelabs/tooling/codelab_rebuild/lib/src/blueprint.g.dart",
"repo_id": "codelabs",
"token_count": 3301
} | 117 |
package com.example.webview_in_flutter
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| codelabs/webview_flutter/step_07/android/app/src/main/kotlin/com/example/webview_in_flutter/MainActivity.kt/0 | {
"file_path": "codelabs/webview_flutter/step_07/android/app/src/main/kotlin/com/example/webview_in_flutter/MainActivity.kt",
"repo_id": "codelabs",
"token_count": 42
} | 118 |
include: ../../analysis_options.yaml
| codelabs/webview_flutter/step_09/analysis_options.yaml/0 | {
"file_path": "codelabs/webview_flutter/step_09/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 12
} | 119 |
// Copyright 2022 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';
import 'package:webview_flutter/webview_flutter.dart';
enum _MenuOptions {
navigationDelegate,
userAgent,
javascriptChannel,
}
class Menu extends StatefulWidget {
const Menu({required this.controller, super.key});
final WebViewController controller;
@override
State<Menu> createState() => _MenuState();
}
class _MenuState extends State<Menu> {
@override
Widget build(BuildContext context) {
return PopupMenuButton<_MenuOptions>(
onSelected: (value) async {
switch (value) {
case _MenuOptions.navigationDelegate:
await widget.controller
.loadRequest(Uri.parse('https://youtube.com'));
case _MenuOptions.userAgent:
final userAgent = await widget.controller
.runJavaScriptReturningResult('navigator.userAgent');
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('$userAgent'),
));
case _MenuOptions.javascriptChannel:
await widget.controller.runJavaScript('''
var req = new XMLHttpRequest();
req.open('GET', "https://api.ipify.org/?format=json");
req.onload = function() {
if (req.status == 200) {
let response = JSON.parse(req.responseText);
SnackBar.postMessage("IP Address: " + response.ip);
} else {
SnackBar.postMessage("Error: " + req.status);
}
}
req.send();''');
}
},
itemBuilder: (context) => [
const PopupMenuItem<_MenuOptions>(
value: _MenuOptions.navigationDelegate,
child: Text('Navigate to YouTube'),
),
const PopupMenuItem<_MenuOptions>(
value: _MenuOptions.userAgent,
child: Text('Show user-agent'),
),
const PopupMenuItem<_MenuOptions>(
value: _MenuOptions.javascriptChannel,
child: Text('Lookup IP Address'),
),
],
);
}
}
| codelabs/webview_flutter/step_10/lib/src/menu.dart/0 | {
"file_path": "codelabs/webview_flutter/step_10/lib/src/menu.dart",
"repo_id": "codelabs",
"token_count": 851
} | 120 |
#import "GeneratedPluginRegistrant.h"
| codelabs/webview_flutter/step_11/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/webview_flutter/step_11/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 121 |
#include "ephemeral/Flutter-Generated.xcconfig"
| devtools/case_study/code_size/optimized/code_size_images/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "devtools/case_study/code_size/optimized/code_size_images/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "devtools",
"token_count": 19
} | 122 |
{
"name": "code_size_images",
"short_name": "code_size_images",
"start_url": ".",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "A flutter project demonstrating code size issues with images",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
{
"src": "icons/Icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/Icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
| devtools/case_study/code_size/optimized/code_size_images/web/manifest.json/0 | {
"file_path": "devtools/case_study/code_size/optimized/code_size_images/web/manifest.json",
"repo_id": "devtools",
"token_count": 314
} | 123 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| devtools/case_study/code_size/optimized/code_size_package/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "devtools/case_study/code_size/optimized/code_size_package/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "devtools",
"token_count": 32
} | 124 |
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "leaking_counter_1",
"request": "launch",
"type": "dart"
},
{
"name": "leaking_counter_1 (profile mode)",
"request": "launch",
"type": "dart",
"flutterMode": "profile"
},
]
} | devtools/case_study/memory_leaks/leaking_counter_1/.vscode/launch.json/0 | {
"file_path": "devtools/case_study/memory_leaks/leaking_counter_1/.vscode/launch.json",
"repo_id": "devtools",
"token_count": 265
} | 125 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="github.nisrulz.usingtabs">
<!-- The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<application android:name="io.flutter.app.FlutterApplication" android:label="using_tabs" android:icon="@mipmap/ic_launcher">
<activity android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
| devtools/case_study/memory_leaks/memory_leak_app/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "devtools/case_study/memory_leaks/memory_leak_app/android/app/src/main/AndroidManifest.xml",
"repo_id": "devtools",
"token_count": 583
} | 126 |
#include "Generated.xcconfig"
| devtools/case_study/memory_leaks/memory_leak_app/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "devtools/case_study/memory_leaks/memory_leak_app/ios/Flutter/Debug.xcconfig",
"repo_id": "devtools",
"token_count": 12
} | 127 |
// Copyright 2019 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 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../common.dart';
import '../logging.dart';
import '../restful_servers.dart';
import 'settings.dart';
/// Create a stateful widget
class MyGetHttpData extends StatefulWidget {
@override
State<MyGetHttpData> createState() => MyGetHttpDataState();
}
// Create the state for our stateful widget
class MyGetHttpDataState extends State<MyGetHttpData> {
MyGetHttpDataState() {
api = currentRestfulAPI = computeUri();
}
final Logging logs = Logging.logging;
late RestfulAPI api;
List? data;
RestfulAPI computeUri() {
switch (restfulApi) {
case '${OpenWeatherMapAPI.friendlyName}':
return OpenWeatherMapAPI();
case '${CitiBikesNYC.friendlyName}':
return CitiBikesNYC();
case '${StarWars.starWarsFilms}':
case '${StarWars.starWarsPeople}':
case '${StarWars.starWarsPlanets}':
case '${StarWars.starWarsSpecies}':
case '${StarWars.starWarsStarships}':
case '${StarWars.starWarsVehicles}':
return StarWars(restfulApi);
default:
return StarWars();
}
}
// Function to get the JSON data
Future<String> getJSONData() async {
// Encode the url
final uri = Uri.encodeFull(api.uri());
logs.add(uri);
final startTime = DateTime.now();
final response = await http.get(
Uri.parse(uri),
// Only accept JSON response
headers: {'Accept': 'application/json'},
);
logs.add(
'Packet received on ${response.headers['date']} '
'content-size ${response.contentLength} bytes '
'elapsed time ${DateTime.now().difference(startTime)}',
);
// To modify the state of the app, use this method
setState(() {
// Get the JSON data
final dataConvertedToJSON = json.decode(response.body);
// Extract the required part and assign it to the global variable named data
data = api.findData(dataConvertedToJSON);
});
return 'Successful';
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Title
title: const Text(appName),
actions: const <Widget>[],
// Set the background color of the App Bar
backgroundColor: Colors.blue,
bottom: PreferredSize(
preferredSize: const Size.fromHeight(48.0),
child: Theme(
// ignore: deprecated_member_use
data: Theme.of(context),
child: Container(
height: 48.0,
alignment: Alignment.center,
child: Text(
currentRestfulAPI.activeFriendlyName,
style: const TextStyle(
fontSize: 24.0,
color: Colors.lightBlueAccent,
),
),
),
),
),
),
// Create a Listview and load the data when available
body: ListView.builder(
itemCount: data == null ? 0 : data!.length,
itemBuilder: (BuildContext context, int index) {
return Center(
child: Column(
// Stretch the cards in horizontal axis
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
child: Container(
padding: const EdgeInsets.all(15.0),
child: Text(
// Read the name field value and set it in the Text widget
api.display(data, index),
// set some style to text
style: const TextStyle(
fontSize: 20.0,
color: Colors.lightBlueAccent,
),
),
),
)
],
),
);
},
),
);
}
@override
void initState() {
super.initState();
// Call the getJSONData() method when the app initializes
unawaited(getJSONData());
}
}
| devtools/case_study/memory_leaks/memory_leak_app/lib/tabs/http_data.dart/0 | {
"file_path": "devtools/case_study/memory_leaks/memory_leak_app/lib/tabs/http_data.dart",
"repo_id": "devtools",
"token_count": 1908
} | 128 |
theme: jekyll-theme-primer
# This should match the path where the live deployment is, so `jekyll serve`
# puts the local version at the same relative path.
baseurl: /devtools
title: DevTools (preview)
# Set the repository so that site.github.xxx works when serving locally.
repository: flutter/devtools
kramdown:
parse_block_html: true
plugins:
- jekyll-redirect-from
| devtools/docs/_config.yml/0 | {
"file_path": "devtools/docs/_config.yml",
"repo_id": "devtools",
"token_count": 114
} | 129 |
{
// Set of configurations to launch devtools_app from VSCode.
//
// The configurations will be picked up by VSCode if the opened folder is devtools_app.
// To access them in VSCode, select the tab "Run and Debug".
//
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "opened test or devtools",
"cwd": "devtools_app",
"request": "launch",
"type": "dart",
},
{
"name": "devtools",
"request": "launch",
"type": "dart",
"program": "lib/main.dart",
},
{
"name": "devtools + experiments",
"request": "launch",
"type": "dart",
"program": "lib/main.dart",
"args": [
"--dart-define=enable_experiments=true"
]
},
{
"name": "devtools - profile",
"request": "launch",
"type": "dart",
"program": "lib/main.dart",
"flutterMode": "profile",
},
{
"name": "memory/default",
"request": "launch",
"type": "dart",
"program": "test/test_infra/scenes/memory/default.stager_app.g.dart",
},
{
"name": "memory/diff_snapshot",
"request": "launch",
"type": "dart",
"program": "test/test_infra/scenes/memory/diff_snapshot.stager_app.g.dart",
},
{
"name": "performance/default",
"request": "launch",
"type": "dart",
"program": "test/test_infra/scenes/performance/default.stager_app.g.dart",
},
{
"name": "attach",
"type": "dart",
"request": "attach",
},
]
}
| devtools/packages/devtools_app/.vscode/launch.json/0 | {
"file_path": "devtools/packages/devtools_app/.vscode/launch.json",
"repo_id": "devtools",
"token_count": 1056
} | 130 |
// Copyright 2023 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.
// Note: this test was modeled after the example test from Flutter Gallery:
// https://github.com/flutter/gallery/blob/master/test_benchmarks/web_bundle_size_test.dart
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:test/test.dart';
// Benchmark size in kB.
const int bundleSizeBenchmark = 4800;
const int gzipBundleSizeBenchmark = 1450;
void main() {
group('Web Compile', () {
test(
'bundle size',
() async {
final js = path.join(
Directory.current.path,
'build',
'web',
'main.dart.js',
);
_logStatus('Building DevTools web app in release mode...');
// These build arguments match the arguments used in the
// tool/lib/commands/build_release.dart command, which is how we build
// DevTools for release.
await _runProcess('flutter', [
'build',
'web',
'--web-renderer',
'canvaskit',
'--pwa-strategy=offline-first',
'--release',
'--no-tree-shake-icons',
]);
_logStatus('Zipping bundle with gzip...');
await _runProcess('gzip', ['-k', '-f', js]);
final bundleSize = await _measureSize(js);
final gzipBundleSize = await _measureSize('$js.gz');
if (bundleSize > bundleSizeBenchmark) {
fail(
'The size the compiled web build "$js" was $bundleSize kB. This is '
'larger than the benchmark that was set at $bundleSizeBenchmark kB.'
'\n\n'
'The build size should be as minimal as possible to reduce the web '
'app\'s initial startup time. If this change is intentional, and'
' expected, please increase the constant "bundleSizeBenchmark".',
);
} else if (gzipBundleSize > gzipBundleSizeBenchmark) {
fail(
'The size the compiled and gzipped web build "$js" was'
' $gzipBundleSize kB. This is larger than the benchmark that was '
'set at $gzipBundleSizeBenchmark kB.\n\n'
'The build size should be as minimal as possible to reduce the '
'web app\'s initial startup time. If this change is intentional, '
'and expected, please increase the constant '
'"gzipBundleSizeBenchmark".',
);
}
},
timeout: const Timeout(Duration(minutes: 5)),
);
});
}
Future<int> _measureSize(String file) async {
final result = await _runProcess('du', ['-k', file]);
return int.parse(
(result.stdout as String).split(RegExp(r'\s+')).first.trim(),
);
}
Future<ProcessResult> _runProcess(
String executable,
List<String> arguments,
) async {
final result = await Process.run(executable, arguments);
stdout.write(result.stdout);
stderr.write(result.stderr);
return result;
}
void _logStatus(String log) {
// ignore: avoid_print, expected log output.
print(log);
}
| devtools/packages/devtools_app/benchmark/web_bundle_size_test.dart/0 | {
"file_path": "devtools/packages/devtools_app/benchmark/web_bundle_size_test.dart",
"repo_id": "devtools",
"token_count": 1283
} | 131 |
// Copyright 2022 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 'package:devtools_shared/devtools_test_utils.dart';
import 'test_infra/run/_in_file_args.dart';
import 'test_infra/run/_utils.dart';
import 'test_infra/run/run_test.dart';
// To run integration tests, run the following from `devtools_app/`:
// `dart run integration_test/run_tests.dart`
//
// To see a list of arguments that you can pass to this test script, please run
// the above command with the '-h' flag.
const _testDirectory = 'integration_test/test';
const _offlineIndicator = 'integration_test/test/offline';
/// The set of test that should be skipped for all devices.
///
/// This list should be empty most of the time, but may contain a broken test
/// while a fix being worked on.
///
/// Format: `'my_example_test.dart'`.
const _skipTests = <String>[
// https://github.com/flutter/devtools/issues/6592
'eval_and_browse_test.dart',
];
void main(List<String> args) async {
final testRunnerArgs = DevToolsAppTestRunnerArgs(
args,
verifyValidTarget: false,
);
await runOneOrManyTests<DevToolsAppTestRunnerArgs>(
testDirectoryPath: _testDirectory,
testRunnerArgs: testRunnerArgs,
runTest: _runTest,
newArgsGenerator: (args) => DevToolsAppTestRunnerArgs(args),
testIsSupported: (testFile) =>
testRunnerArgs.testAppDevice.supportsTest(testFile.path),
debugLogging: debugTestScript,
);
}
Future<void> _runTest(
DevToolsAppTestRunnerArgs testRunnerArgs,
) async {
final testTarget = testRunnerArgs.testTarget!;
final shouldSkip = _skipTests.any((t) => testTarget.endsWith(t));
if (shouldSkip) return;
if (!testRunnerArgs.testAppDevice.supportsTest(testTarget)) {
// Skip test, since it is not supported for device.
return;
}
await runFlutterIntegrationTest(
testRunnerArgs,
TestFileArgs(testTarget, testAppDevice: testRunnerArgs.testAppDevice),
offline: testTarget.startsWith(_offlineIndicator),
);
}
| devtools/packages/devtools_app/integration_test/run_tests.dart/0 | {
"file_path": "devtools/packages/devtools_app/integration_test/run_tests.dart",
"repo_id": "devtools",
"token_count": 684
} | 132 |
// Copyright 2022 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.
// ignore_for_file: avoid_print
import 'dart:async';
import 'dart:convert';
import 'package:args/args.dart';
import 'package:devtools_shared/devtools_test_utils.dart';
import '_in_file_args.dart';
import '_test_app_driver.dart';
import '_utils.dart';
/// Runs one test.
///
/// Do not use this method directly, but instead use the run_tests.dart
/// which performs essential set up steps.
Future<void> runFlutterIntegrationTest(
DevToolsAppTestRunnerArgs testRunnerArgs,
TestFileArgs testFileArgs, {
required bool offline,
}) async {
IntegrationTestApp? testApp;
late String testAppUri;
if (!offline) {
if (testRunnerArgs.testAppUri == null) {
debugLog('Starting a test application');
// Create the test app and start it.
try {
if (testRunnerArgs.testAppDevice == TestAppDevice.cli) {
debugLog(
'Creating a TestDartCliApp with path ${testFileArgs.appPath}',
);
testApp = TestDartCliApp(appPath: testFileArgs.appPath);
} else {
debugLog(
'Creating a TestFlutterApp with path ${testFileArgs.appPath} and '
'device ${testRunnerArgs.testAppDevice}',
);
testApp = TestFlutterApp(
appPath: testFileArgs.appPath,
appDevice: testRunnerArgs.testAppDevice,
);
}
await testApp.start();
} catch (e) {
// ignore: avoid-throw-in-catch-block, by design
throw Exception('Error starting test app: $e');
}
testAppUri = testApp.vmServiceUri.toString();
} else {
testAppUri = testRunnerArgs.testAppUri!;
}
}
// Run the flutter integration test.
final testRunner = IntegrationTestRunner();
try {
final testArgs = <String, Object>{
if (!offline) 'service_uri': testAppUri,
};
await testRunner.run(
testRunnerArgs.testTarget!,
testDriver: 'test_driver/integration_test.dart',
headless: testRunnerArgs.headless,
dartDefineArgs: [
'test_args=${jsonEncode(testArgs)}',
if (testFileArgs.experimentsOn) 'enable_experiments=true',
if (testRunnerArgs.updateGoldens) 'update_goldens=true',
],
debugLogging: debugTestScript,
);
} finally {
if (testApp != null) {
debugLog('killing the test app');
await testApp.stop();
}
debugLog('cancelling stream subscriptions');
await testRunner.cancelAllStreamSubscriptions();
}
}
class DevToolsAppTestRunnerArgs extends IntegrationTestRunnerArgs {
DevToolsAppTestRunnerArgs(super.args, {super.verifyValidTarget = true})
: super(addExtraArgs: _addExtraArgs) {
testAppDevice = TestAppDevice.fromArgName(
argResults[_testAppDeviceArg] ?? TestAppDevice.flutterTester.argName,
)!;
}
/// The type of device for the test app to run on.
late final TestAppDevice testAppDevice;
/// The Vm Service URI for the test app to connect devtools to.
///
/// This value will only be used for tests with live connection.
String? get testAppUri => argResults[_testAppUriArg];
/// Whether golden images should be updated with the result of this test run.
bool get updateGoldens => argResults[_updateGoldensArg];
static const _testAppUriArg = 'test-app-uri';
static const _testAppDeviceArg = 'test-app-device';
static const _updateGoldensArg = 'update-goldens';
/// Adds additional argument handlers to [argParser] that are specific to
/// integration tests in package:devtools_app.
static void _addExtraArgs(ArgParser argParser) {
argParser
..addOption(
_testAppUriArg,
help: 'The vm service connection to use for the app that DevTools will '
'connect to during the integration test. If left empty, a sample app '
'will be spun up as part of the integration test process.',
)
..addOption(
_testAppDeviceArg,
help:
'The device to use for the test app that DevTools will connect to.',
)
..addFlag(
_updateGoldensArg,
negatable: false,
help: 'Updates the golden images with the results of this test run.',
);
}
}
| devtools/packages/devtools_app/integration_test/test_infra/run/run_test.dart/0 | {
"file_path": "devtools/packages/devtools_app/integration_test/test_infra/run/run_test.dart",
"repo_id": "devtools",
"token_count": 1619
} | 133 |
// Copyright 2023 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 'package:devtools_app_shared/utils.dart';
import 'package:devtools_shared/devtools_extensions.dart';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import '../shared/globals.dart';
import '../shared/server/server.dart' as server;
final _log = Logger('ExtensionService');
class ExtensionService extends DisposableController
with AutoDisposeControllerMixin {
ExtensionService({this.fixedAppRoot});
/// The fixed (unchanging) root file:// URI for the application this
/// [ExtensionService] will manage DevTools extensions for.
///
/// When null, the root will be calculated from the [serviceManager]'s
/// currently connected app. See [_initAppRoot].
final Uri? fixedAppRoot;
/// The root file:// URI for the Dart / Flutter application this
/// [ExtensionService] will manage DevTools extensions for.
Uri? _appRoot;
/// All the DevTools extensions that are available for the connected
/// application, regardless of whether they have been enabled or disabled
/// by the user.
ValueListenable<List<DevToolsExtensionConfig>> get availableExtensions =>
_availableExtensions;
final _availableExtensions = ValueNotifier<List<DevToolsExtensionConfig>>([]);
/// DevTools extensions that are visible in their own DevTools screen (i.e.
/// extensions that have not been manually disabled by the user).
ValueListenable<List<DevToolsExtensionConfig>> get visibleExtensions =>
_visibleExtensions;
final _visibleExtensions = ValueNotifier<List<DevToolsExtensionConfig>>([]);
/// Returns the [ValueListenable] that stores the [ExtensionEnabledState] for
/// the DevTools Extension with [extensionName].
ValueListenable<ExtensionEnabledState> enabledStateListenable(
String extensionName,
) {
return _extensionEnabledStates.putIfAbsent(
extensionName.toLowerCase(),
() => ValueNotifier<ExtensionEnabledState>(
ExtensionEnabledState.none,
),
);
}
/// Whether extensions are actively being refreshed by the DevTools server.
ValueListenable<bool> get refreshInProgress => _refreshInProgress;
final _refreshInProgress = ValueNotifier(false);
final _extensionEnabledStates =
<String, ValueNotifier<ExtensionEnabledState>>{};
Future<void> initialize() async {
await _initAppRoot();
await _maybeRefreshExtensions();
cancelListeners();
// We only need to add VM service manager related listeners when we are
// interacting with the currently connected app (i.e. when
// [fixedAppRootUri] is null).
if (fixedAppRoot == null) {
addAutoDisposeListener(
serviceConnection.serviceManager.connectedState,
() async {
if (serviceConnection.serviceManager.connectedState.value.connected) {
_log.fine(
'established new app connection. Initializing and refreshing.',
);
await _initAppRoot();
await _maybeRefreshExtensions();
} else {
_log.fine('app disconnected. Initializing and refreshing.');
_reset();
}
},
);
// TODO(https://github.com/flutter/flutter/issues/134470): refresh on
// hot reload and hot restart events instead.
addAutoDisposeListener(
serviceConnection.serviceManager.isolateManager.mainIsolate,
() async {
if (serviceConnection
.serviceManager.isolateManager.mainIsolate.value !=
null) {
_log.fine('main isolate changed. Initializing and refreshing.');
await _initAppRoot();
await _maybeRefreshExtensions();
} else {
_reset();
}
},
);
}
addAutoDisposeListener(
preferences.devToolsExtensions.showOnlyEnabledExtensions,
() async {
await _refreshExtensionEnabledStates();
},
);
// TODO(kenz): we should also refresh the available extensions on some event
// from the analysis server that is watching the
// .dart_tool/package_config.json file for changes.
}
Future<void> _initAppRoot() async {
_appRoot = fixedAppRoot ?? await _connectedAppRoot();
}
Future<void> _maybeRefreshExtensions() async {
if (_appRoot == null) return;
_refreshInProgress.value = true;
_availableExtensions.value =
await server.refreshAvailableExtensions(_appRoot!)
..sort();
await _refreshExtensionEnabledStates();
_refreshInProgress.value = false;
}
Future<void> _refreshExtensionEnabledStates() async {
if (_appRoot == null) return;
final onlyIncludeEnabled =
preferences.devToolsExtensions.showOnlyEnabledExtensions.value;
final visible = <DevToolsExtensionConfig>[];
for (final extension in _availableExtensions.value) {
final stateFromOptionsFile = await server.extensionEnabledState(
appRoot: _appRoot!,
extensionName: extension.name,
);
final stateNotifier = _extensionEnabledStates.putIfAbsent(
extension.name,
() => ValueNotifier<ExtensionEnabledState>(stateFromOptionsFile),
);
stateNotifier.value = stateFromOptionsFile;
final shouldIncludeInVisible = onlyIncludeEnabled
? stateFromOptionsFile == ExtensionEnabledState.enabled
: stateFromOptionsFile != ExtensionEnabledState.disabled;
if (shouldIncludeInVisible) {
visible.add(extension);
}
}
_log.fine(
'visible extensions after refreshing - ${visible.map((e) => e.name).toList()}',
);
// [_visibleExtensions] should be set last so that all extension states in
// [_extensionEnabledStates] are updated by the time we notify listeners of
// [visibleExtensions]. It is not necessary to sort [visible] because
// [_availableExtensions] is already sorted.
_visibleExtensions.value = visible;
}
/// Sets the enabled state for [extension].
Future<void> setExtensionEnabledState(
DevToolsExtensionConfig extension, {
required bool enable,
}) async {
if (_appRoot == null) return;
await server.extensionEnabledState(
appRoot: _appRoot!,
extensionName: extension.name,
enable: enable,
);
await _refreshExtensionEnabledStates();
}
void _reset() {
_appRoot = null;
_availableExtensions.value = [];
_visibleExtensions.value = [];
_extensionEnabledStates.clear();
_refreshInProgress.value = false;
}
}
Future<Uri?> _connectedAppRoot() async {
final packageUriString =
await serviceConnection.rootPackageDirectoryForMainIsolate();
if (packageUriString == null) return null;
return Uri.parse(packageUriString);
}
| devtools/packages/devtools_app/lib/src/extensions/extension_service.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/extensions/extension_service.dart",
"repo_id": "devtools",
"token_count": 2327
} | 134 |
// Copyright 2020 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:devtools_app_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:devtools_shared/devtools_shared.dart';
import 'package:flutter/material.dart';
import 'package:vm_snapshot_analysis/precompiler_trace.dart';
import '../../shared/analytics/analytics.dart' as ga;
import '../../shared/analytics/constants.dart' as gac;
import '../../shared/charts/treemap.dart';
import '../../shared/common_widgets.dart';
import '../../shared/config_specific/drag_and_drop/drag_and_drop.dart';
import '../../shared/file_import.dart';
import '../../shared/globals.dart';
import '../../shared/primitives/utils.dart';
import '../../shared/screen.dart';
import '../../shared/server/server.dart' as server;
import '../../shared/ui/tab.dart';
import '../../shared/utils.dart';
import 'app_size_controller.dart';
import 'app_size_table.dart';
import 'code_size_attribution.dart';
const initialFractionForTreemap = 0.67;
const initialFractionForTreeTable = 0.33;
class AppSizeScreen extends Screen {
AppSizeScreen() : super.fromMetaData(ScreenMetaData.appSize);
static const analysisTabKey = Key('Analysis Tab');
static const diffTabKey = Key('Diff Tab');
static final id = ScreenMetaData.appSize.id;
@visibleForTesting
static const diffTypeDropdownKey = Key('Diff Tree Type Dropdown');
@visibleForTesting
static const appUnitDropdownKey = Key('App Segment Dropdown');
@visibleForTesting
static const analysisViewTreemapKey = Key('Analysis View Treemap');
@visibleForTesting
static const diffViewTreemapKey = Key('Diff View Treemap');
static const loadingMessage =
'Loading data...\nPlease do not refresh or leave this page.';
@override
String get docPageId => id;
@override
Widget buildScreenBody(BuildContext context) {
// Since `handleDrop` is not specified for this [DragAndDrop] widget, drag
// and drop events will be absorbed by it, meaning drag and drop actions
// will be a no-op if they occur over this area. [DragAndDrop] widgets
// lower in the tree will have priority over this one.
return const DragAndDrop(child: AppSizeBody());
}
}
class AppSizeBody extends StatefulWidget {
const AppSizeBody({super.key});
@override
State<AppSizeBody> createState() => _AppSizeBodyState();
}
class _AppSizeBodyState extends State<AppSizeBody>
with
AutoDisposeMixin,
SingleTickerProviderStateMixin,
ProvidedControllerMixin<AppSizeController, AppSizeBody> {
static const _gaPrefix = 'appSizeTab';
static final diffTab = DevToolsTab.create(
tabName: 'Diff',
gaPrefix: _gaPrefix,
key: AppSizeScreen.diffTabKey,
);
static final analysisTab = DevToolsTab.create(
tabName: 'Analysis',
gaPrefix: _gaPrefix,
key: AppSizeScreen.analysisTabKey,
);
static final tabs = [analysisTab, diffTab];
late final TabController _tabController;
bool _preLoadingData = false;
@override
void initState() {
super.initState();
ga.screen(gac.appSize);
_tabController = TabController(length: tabs.length, vsync: this);
addAutoDisposeListener(_tabController);
}
Future<void> maybeLoadAppSizeFiles() async {
final queryParams = loadQueryParams();
final baseFilePath = queryParams[baseAppSizeFilePropertyName];
if (baseFilePath != null) {
// TODO(kenz): does this have to be in a setState()?
_preLoadingData = true;
final baseAppSizeFile = await server.requestBaseAppSizeFile(baseFilePath);
DevToolsJsonFile? testAppSizeFile;
final testFilePath = queryParams[testAppSizeFilePropertyName];
if (testFilePath != null) {
testAppSizeFile = await server.requestTestAppSizeFile(testFilePath);
}
// TODO(kenz): add error handling if the files are null
if (baseAppSizeFile != null) {
if (testAppSizeFile != null) {
controller.loadDiffTreeFromJsonFiles(
oldFile: baseAppSizeFile,
newFile: testAppSizeFile,
onError: _pushErrorMessage,
);
_tabController.animateTo(tabs.indexOf(diffTab));
} else {
controller.loadTreeFromJsonFile(
jsonFile: baseAppSizeFile,
onError: _pushErrorMessage,
);
_tabController.animateTo(tabs.indexOf(analysisTab));
}
}
}
if (_preLoadingData) {
setState(() {
_preLoadingData = false;
});
}
}
@override
void dispose() {
super.dispose();
_tabController.dispose();
}
void _pushErrorMessage(String error) {
if (mounted) notificationService.pushError(error);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!initController()) return;
unawaited(maybeLoadAppSizeFiles());
addAutoDisposeListener(controller.activeDiffTreeType);
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<bool>(
valueListenable: controller.isDeferredApp,
builder: (context, isDeferredApp, _) {
if (_preLoadingData) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
devToolsExtensionPoints.loadingAppSizeDataMessage(),
textAlign: TextAlign.center,
),
const SizedBox(height: defaultSpacing),
const CircularProgressIndicator(),
],
),
);
}
final currentTab = tabs[_tabController.index];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: defaultButtonHeight,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TabBar(
labelColor: Theme.of(context).textTheme.bodyLarge!.color,
isScrollable: true,
controller: _tabController,
tabs: tabs,
),
Row(
children: [
if (isDeferredApp) _buildAppUnitDropdown(currentTab.key!),
if (currentTab.key == AppSizeScreen.diffTabKey) ...[
const SizedBox(width: defaultSpacing),
_buildDiffTreeTypeDropdown(),
],
const SizedBox(width: defaultSpacing),
_buildClearButton(currentTab.key!),
],
),
],
),
),
Expanded(
child: TabBarView(
physics: defaultTabBarViewPhysics,
controller: _tabController,
children: const [
AnalysisView(),
DiffView(),
],
),
),
],
);
},
);
}
DropdownButtonHideUnderline _buildDiffTreeTypeDropdown() {
return DropdownButtonHideUnderline(
key: AppSizeScreen.diffTypeDropdownKey,
child: DropdownButton<DiffTreeType>(
value: controller.activeDiffTreeType.value,
items: [
_buildDiffTreeTypeMenuItem(DiffTreeType.combined),
_buildDiffTreeTypeMenuItem(DiffTreeType.increaseOnly),
_buildDiffTreeTypeMenuItem(DiffTreeType.decreaseOnly),
],
onChanged: (newDiffTreeType) {
controller.changeActiveDiffTreeType(newDiffTreeType!);
},
),
);
}
DropdownButtonHideUnderline _buildAppUnitDropdown(Key tabKey) {
return DropdownButtonHideUnderline(
key: AppSizeScreen.appUnitDropdownKey,
child: DropdownButton<AppUnit>(
value: controller.selectedAppUnit.value,
items: [
_buildAppUnitMenuItem(AppUnit.entireApp),
_buildAppUnitMenuItem(AppUnit.mainOnly),
_buildAppUnitMenuItem(AppUnit.deferredOnly),
],
onChanged: (newAppUnit) {
setState(() {
controller.changeSelectedAppUnit(newAppUnit!, tabKey);
});
},
),
);
}
DropdownMenuItem<DiffTreeType> _buildDiffTreeTypeMenuItem(
DiffTreeType diffTreeType,
) {
return DropdownMenuItem<DiffTreeType>(
value: diffTreeType,
child: Text(diffTreeType.display),
);
}
DropdownMenuItem<AppUnit> _buildAppUnitMenuItem(AppUnit appUnit) {
return DropdownMenuItem<AppUnit>(
value: appUnit,
child: Text(appUnit.display),
);
}
Widget _buildClearButton(Key activeTabKey) {
return ClearButton(
gaScreen: gac.appSize,
gaSelection: gac.clear,
onPressed: () => controller.clear(activeTabKey),
);
}
}
class AnalysisView extends StatefulWidget {
const AnalysisView({super.key});
// TODO(kenz): add links to documentation on how to generate these files, and
// mention the import file button once it is hooked up to a file picker.
static const importInstructions = 'Drag and drop an AOT snapshot or'
' size analysis file for debugging';
@override
State<AnalysisView> createState() => _AnalysisViewState();
}
class _AnalysisViewState extends State<AnalysisView>
with
AutoDisposeMixin,
ProvidedControllerMixin<AppSizeController, AnalysisView> {
TreemapNode? analysisRoot;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!initController()) return;
analysisRoot = controller.analysisRoot.value.node;
addAutoDisposeListener(controller.analysisRoot, () {
setState(() {
analysisRoot = controller.analysisRoot.value.node;
});
});
addAutoDisposeListener(controller.analysisJsonFile);
}
@override
Widget build(BuildContext context) {
final analysisRootLocal = analysisRoot;
return Column(
children: [
Expanded(
child: analysisRootLocal == null
? _buildImportFileView()
: _AppSizeView(
title: _generateSingleFileHeaderText(),
treemapKey: AppSizeScreen.analysisViewTreemapKey,
treemapRoot: analysisRootLocal,
onRootChangedCallback: controller.changeAnalysisRoot,
analysisTable: AppSizeAnalysisTable(
rootNode: analysisRootLocal.root,
controller: controller,
),
callGraphRoot: controller.analysisCallGraphRoot.value,
),
),
],
);
}
String _generateSingleFileHeaderText() {
final analysisFile = controller.analysisJsonFile.value!;
String output = analysisFile.isAnalyzeSizeFile
? 'Total size analysis: '
: 'Dart AOT snapshot: ';
output += analysisFile.displayText;
return output;
}
Widget _buildImportFileView() {
return ValueListenableBuilder<bool>(
valueListenable: controller.processingNotifier,
builder: (context, processing, _) {
if (processing) {
return Center(
child: Text(
AppSizeScreen.loadingMessage,
textAlign: TextAlign.center,
style: TextStyle(
color: Theme.of(context).textTheme.displayLarge!.color,
),
),
);
} else {
return Column(
children: [
Flexible(
child: FileImportContainer(
title: 'Size analysis',
instructions: AnalysisView.importInstructions,
actionText: 'Analyze Size',
gaScreen: gac.appSize,
gaSelectionImport: gac.importFileSingle,
gaSelectionAction: gac.analyzeSingle,
onAction: (jsonFile) {
controller.loadTreeFromJsonFile(
jsonFile: jsonFile,
onError: (error) {
if (mounted) notificationService.push(error);
},
);
},
),
),
],
);
}
},
);
}
}
class DiffView extends StatefulWidget {
const DiffView({super.key});
// TODO(kenz): add links to documentation on how to generate these files, and
// mention the import file button once it is hooked up to a file picker.
static const importOldInstructions = 'Drag and drop an original (old) AOT '
'snapshot or size analysis file for debugging';
static const importNewInstructions = 'Drag and drop a modified (new) AOT '
'snapshot or size analysis file for debugging';
@override
State<DiffView> createState() => _DiffViewState();
}
class _DiffViewState extends State<DiffView>
with
AutoDisposeMixin,
ProvidedControllerMixin<AppSizeController, DiffView> {
TreemapNode? diffRoot;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!initController()) return;
diffRoot = controller.diffRoot.value;
addAutoDisposeListener(controller.diffRoot, () {
setState(() {
diffRoot = controller.diffRoot.value;
});
});
addAutoDisposeListener(controller.activeDiffTreeType);
addAutoDisposeListener(controller.oldDiffJsonFile);
addAutoDisposeListener(controller.newDiffJsonFile);
}
@override
Widget build(BuildContext context) {
final diffRootLocal = diffRoot;
return Column(
children: [
Expanded(
child: diffRootLocal == null
? _buildImportDiffView()
: _AppSizeView(
title: _generateDualFileHeaderText(),
treemapKey: AppSizeScreen.diffViewTreemapKey,
treemapRoot: diffRootLocal,
onRootChangedCallback: controller.changeDiffRoot,
analysisTable: AppSizeDiffTable(rootNode: diffRootLocal),
callGraphRoot: controller.diffCallGraphRoot.value,
),
),
],
);
}
String _generateDualFileHeaderText() {
final oldFile = controller.oldDiffJsonFile.value!;
final newFile = controller.newDiffJsonFile.value!;
String output = 'Diffing ';
output += oldFile.isAnalyzeSizeFile
? 'total size analyses: '
: 'Dart AOT snapshots: ';
output += oldFile.displayText;
output += ' (OLD) vs (NEW) ';
output += newFile.displayText;
return output;
}
Widget _buildImportDiffView() {
return ValueListenableBuilder<bool>(
valueListenable: controller.processingNotifier,
builder: (context, processing, _) {
if (processing) {
return _buildLoadingMessage();
} else {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: DualFileImportContainer(
firstFileTitle: 'Old',
secondFileTitle: 'New',
// TODO(kenz): perhaps bold "original" and "modified".
firstInstructions: DiffView.importOldInstructions,
secondInstructions: DiffView.importNewInstructions,
actionText: 'Analyze Diff',
gaScreen: gac.appSize,
gaSelectionImportFirst: gac.importFileDiffFirst,
gaSelectionImportSecond: gac.importFileDiffSecond,
gaSelectionAction: gac.analyzeDiff,
onAction: (oldFile, newFile, onError) =>
controller.loadDiffTreeFromJsonFiles(
oldFile: oldFile,
newFile: newFile,
onError: onError,
),
),
),
],
);
}
},
);
}
Widget _buildLoadingMessage() {
return Center(
child: Text(
AppSizeScreen.loadingMessage,
textAlign: TextAlign.center,
style: TextStyle(
color: Theme.of(context).textTheme.displayLarge!.color,
),
),
);
}
}
class _AppSizeView extends StatelessWidget {
const _AppSizeView({
required this.title,
required this.treemapKey,
required this.treemapRoot,
required this.onRootChangedCallback,
required this.analysisTable,
required this.callGraphRoot,
});
final String title;
final Key treemapKey;
final TreemapNode treemapRoot;
final void Function(TreemapNode?) onRootChangedCallback;
final Widget analysisTable;
final CallGraphNode? callGraphRoot;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: intermediateSpacing),
child: RoundedOutlinedBorder(
clip: true,
child: Column(
children: [
AreaPaneHeader(
title: Text(title),
maxLines: 2,
roundedTopBorder: false,
includeTopBorder: false,
),
Expanded(
child: SplitPane(
axis: Axis.vertical,
initialFractions: const [
initialFractionForTreemap,
initialFractionForTreeTable,
],
children: [
LayoutBuilder(
key: treemapKey,
builder: (context, constraints) {
return Treemap.fromRoot(
rootNode: treemapRoot,
levelsVisible: 2,
isOutermostLevel: true,
width: constraints.maxWidth,
height: constraints.maxHeight,
onRootChangedCallback: onRootChangedCallback,
);
},
),
OutlineDecoration.onlyTop(
child: Row(
children: [
Flexible(
child: analysisTable,
),
if (callGraphRoot != null)
Flexible(
child: OutlineDecoration.onlyLeft(
child: CallGraphWithDominators(
callGraphRoot: callGraphRoot!,
),
),
),
],
),
),
],
),
),
],
),
),
);
}
}
| devtools/packages/devtools_app/lib/src/screens/app_size/app_size_screen.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/app_size/app_size_screen.dart",
"repo_id": "devtools",
"token_count": 8568
} | 135 |
// Copyright 2021 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:devtools_app_shared/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:vm_service/vm_service.dart';
import '../../shared/globals.dart';
import '../../shared/primitives/trees.dart';
import '../vm_developer/vm_service_private_extensions.dart';
import 'program_explorer_model.dart';
class ProgramExplorerController extends DisposableController
with AutoDisposeControllerMixin {
/// [showCodeNodes] controls whether or not [Code] nodes are displayed in the
/// outline view.
ProgramExplorerController({
this.showCodeNodes = false,
});
/// The outline view nodes for the currently selected library.
ValueListenable<List<VMServiceObjectNode>> get outlineNodes => _outlineNodes;
final _outlineNodes = ListValueNotifier<VMServiceObjectNode>([]);
ValueListenable<bool> get isLoadingOutline => _isLoadingOutline;
final _isLoadingOutline = ValueNotifier<bool>(false);
/// The currently selected node in the Program Explorer file picker.
@visibleForTesting
VMServiceObjectNode? get scriptSelection => _scriptSelection;
VMServiceObjectNode? _scriptSelection;
/// The processed roots of the tree.
ValueListenable<List<VMServiceObjectNode>> get rootObjectNodes =>
rootObjectNodesInternal;
@visibleForTesting
final rootObjectNodesInternal = ListValueNotifier<VMServiceObjectNode>([]);
ValueListenable<int> get selectedNodeIndex => _selectedNodeIndex;
final _selectedNodeIndex = ValueNotifier<int>(0);
/// The currently selected node in the Program Explorer outline.
VMServiceObjectNode? _outlineSelection;
/// Notifies that the controller has finished initializing.
ValueListenable<bool> get initialized => _initialized;
final _initialized = ValueNotifier<bool>(false);
bool _initializing = false;
/// Controls whether or not [Code] nodes are displayed in the outline view.
final bool showCodeNodes;
/// Returns true if [function] is a getter or setter that was not explicitly
/// defined (e.g., `int foo` creates `int get foo` and `set foo(int)`).
static bool _isSyntheticAccessor(FuncRef function, List<FieldRef> fields) {
for (final field in fields) {
if (function.name == field.name || function.name == '${field.name}=') {
return true;
}
}
return false;
}
/// Initializes the program structure.
Future<void> initialize() async {
if (_initializing) {
return;
}
_initializing = true;
final isolate =
serviceConnection.serviceManager.isolateManager.selectedIsolate.value;
final libraries = isolate != null
? serviceConnection.serviceManager.isolateManager
.isolateState(isolate)
.isolateNow!
.libraries!
: <LibraryRef>[];
if (scriptManager.sortedScripts.value.isEmpty && isolate != null) {
await scriptManager.retrieveAndSortScripts(isolate);
}
// Build the initial tree.
final nodes = VMServiceObjectNode.createRootsFrom(
this,
libraries,
);
rootObjectNodesInternal.replaceAll(nodes);
_initialized.value = true;
}
void initListeners() {
// Re-initialize after reload.
// TODO(elliette): If file was opened from before the reload, we should try
// to open that one instead of the entrypoint file.
addAutoDisposeListener(
scriptManager.sortedScripts,
refresh,
);
}
Future<void> selectScriptNode(ScriptRef? script) async {
if (!initialized.value) {
return;
}
if (script == null) {
clearSelection();
return;
}
await _selectScriptNode(script, rootObjectNodesInternal.value);
rootObjectNodesInternal.notifyListeners();
}
Future<void> _selectScriptNode(
ScriptRef? script,
List<VMServiceObjectNode> nodes,
) async {
bool searchCondition(VMServiceObjectNode node) =>
node.script?.uri == script!.uri;
for (final node in nodes) {
final result = node.firstChildWithCondition(searchCondition);
if (result != null) {
await selectNode(result);
result.expandAscending();
_selectedNodeIndex.value = _calculateNodeIndex(
matchingNodeCondition: searchCondition,
includeCollapsedNodes: false,
);
return;
}
}
}
VMServiceObjectNode? findOutlineNode(ObjRef object) {
return breadthFirstSearchObject(object, _outlineNodes.value);
}
int _calculateNodeIndex({
bool Function(VMServiceObjectNode node)? matchingNodeCondition,
bool includeCollapsedNodes = true,
}) {
// Index tracks the position of the node in the flat-list representation of
// the tree:
var index = 0;
for (final node in rootObjectNodesInternal.value) {
final matchingNode = depthFirstTraversal(
node,
returnCondition: matchingNodeCondition,
exploreChildrenCondition: includeCollapsedNodes
? null
: (VMServiceObjectNode node) => node.isExpanded,
action: (VMServiceObjectNode _) => index++,
);
if (matchingNode != null) return index;
}
// If the node wasn't found, return -1.
return -1;
}
/// Clears controller state and re-initializes.
Future<void> refresh() {
_scriptSelection = null;
_outlineSelection = null;
_isLoadingOutline.value = true;
_outlineNodes.clear();
_initialized.value = false;
_initializing = false;
return initialize();
}
void clearSelection() {
_scriptSelection?.unselect();
_scriptSelection = null;
_outlineNodes.clear();
_outlineSelection = null;
rootObjectNodesInternal.notifyListeners();
}
void clearOutlineSelection() {
_outlineSelection?.unselect();
_outlineSelection = null;
_outlineNodes.notifyListeners();
}
/// Marks [node] as the currently selected node, clearing the selection state
/// of any currently selected node.
Future<void> selectNode(VMServiceObjectNode node) async {
if (!node.isSelectable) {
return;
}
if (_scriptSelection != node) {
await populateNode(node);
node.select();
_scriptSelection?.unselect();
_scriptSelection = node;
_isLoadingOutline.value = true;
_outlineSelection = null;
final newOutlineNodes = await _scriptSelection!.outline;
if (newOutlineNodes != null) {
_outlineNodes.replaceAll(newOutlineNodes);
}
_isLoadingOutline.value = false;
}
}
void selectOutlineNode(VMServiceObjectNode node) {
if (!node.isSelectable) {
return;
}
if (_outlineSelection != node) {
node.select();
_outlineSelection?.unselect();
_outlineSelection = node;
_outlineNodes.notifyListeners();
}
}
/// Sets the current [_outlineSelection] value to null, and resets the
/// [_outlineNodes] tree for the current [_scriptSelection] by
/// collapsing and unselecting all nodes.
void resetOutline() {
_outlineSelection = null;
for (final node in _outlineNodes.value) {
breadthFirstTraversal<VMServiceObjectNode>(
node,
action: (VMServiceObjectNode node) {
node
..collapse()
..unselect();
},
);
}
_outlineNodes.notifyListeners();
}
void expandToNode(VMServiceObjectNode node) {
node.expandAscending();
_outlineNodes.notifyListeners();
}
/// Updates `node` with a fully populated VM service [Obj].
///
/// If `node.object` is already an instance of [Obj], this function
/// immediately returns.
Future<void> populateNode(VMServiceObjectNode node) async {
final object = node.object;
final service = serviceConnection.serviceManager.service;
final isolateId = serviceConnection
.serviceManager.isolateManager.selectedIsolate.value!.id;
Future<List<Obj>> getObjects(Iterable<ObjRef> objs) {
return Future.wait(
objs.map(
(o) => service!.getObject(isolateId!, o.id!),
),
);
}
Future<List<Func>> getFuncs(
Iterable<FuncRef> funcs,
Iterable<FieldRef>? fields,
) async {
final res = await Future.wait<Func>(
funcs
.where((f) => !_isSyntheticAccessor(f, fields as List<FieldRef>))
.map<Future<Func>>(
(f) => service!.getObject(isolateId!, f.id!).then((f) async {
final func = f as Func;
final codeRef = func.code;
// Populate the [Code] objects in each function if we want to
// show code nodes in the outline.
if (showCodeNodes && codeRef != null) {
final code =
await service.getObject(isolateId, codeRef.id!) as Code;
func.code = code;
Code unoptimizedCode = code;
// `func.code` could be unoptimized code, so don't bother
// fetching it again.
if (func.unoptimizedCode != null &&
func.unoptimizedCode?.id! != code.id!) {
unoptimizedCode = await service.getObject(
isolateId,
func.unoptimizedCode!.id!,
) as Code;
}
func.unoptimizedCode = unoptimizedCode;
}
return func;
}),
),
);
return res.cast<Func>();
}
try {
if (object == null || object is Obj) {
return;
} else if (object is LibraryRef) {
final lib = await service!.getObject(isolateId!, object.id!) as Library;
final results = await Future.wait([
getObjects(lib.variables!),
getFuncs(lib.functions!, lib.variables),
]);
lib.variables = results[0].cast<Field>();
lib.functions = results[1].cast<Func>();
node.updateObject(lib);
} else if (object is ClassRef) {
final clazz = await service!.getObject(isolateId!, object.id!) as Class;
final results = await Future.wait([
getObjects(clazz.fields!),
getFuncs(clazz.functions!, clazz.fields),
]);
clazz.fields = results[0].cast<Field>();
clazz.functions = results[1].cast<Func>();
node.updateObject(clazz);
} else {
final obj = await service!.getObject(isolateId!, object.id!);
node.updateObject(obj);
}
} on RPCError {
// Swallow RPC errors that can be caused by the service disappearing.
}
}
/// Searches and returns the script or library node in the FileExplorer
/// which is the source location of the target [object].
Future<VMServiceObjectNode> searchFileExplorer(ObjRef object) async {
final service = serviceConnection.serviceManager.service!;
final isolateId = serviceConnection
.serviceManager.isolateManager.selectedIsolate.value!.id!;
// If `object` is a library, it will always be a root node and is simple to
// find.
if (object is LibraryRef) {
final result = _searchRootObjectNodes(object)!;
await result.populateLocation();
return result;
}
// Otherwise, we need to find the target script to determine the library
// the target node is listed under.
final ScriptRef? targetScript = switch (object) {
ClassRef(:final location?) ||
FieldRef(:final location?) ||
FuncRef(:final location?) =>
location.script,
Code(:final function?) => function.location?.script,
ScriptRef() => object,
_ => null,
};
if (targetScript == null) {
throw StateError('Could not find script');
}
final scriptObj =
await service.getObject(isolateId, targetScript.id!) as Script;
final LibraryRef targetLib = scriptObj.library!;
// Search targetLib only on the root level nodes (this is the most common
// scenario).
var libNode = _searchRootObjectNodes(targetLib);
// If we couldn't find the target library as a root node, it's possible we
// have a library defined using the `library` keyword by the user, which
// will likely be under a directory node.
libNode ??= breadthFirstSearchObject(
scriptObj,
rootObjectNodes.value,
);
// If the object's owning script URI is the same as the target library URI,
// return the library node as the match.
if (targetLib.uri == targetScript.uri) {
return libNode!;
}
// Find the script node nested under the library.
final scriptNode = breadthFirstSearchObject(
targetScript,
rootObjectNodes.value,
);
if (scriptNode == null) {
throw StateError('Could not find script node');
}
await scriptNode.populateLocation();
return scriptNode;
}
VMServiceObjectNode? _searchRootObjectNodes(ObjRef obj) {
for (final rootNode in rootObjectNodes.value) {
if (rootNode.object?.id == obj.id) {
return rootNode;
}
}
return null;
}
/// Performs a breath first search on the list of roots and returns the
/// first node whose object is the same as the target [obj].
VMServiceObjectNode? breadthFirstSearchObject(
ObjRef obj,
List<VMServiceObjectNode> roots,
) {
for (final root in roots) {
final match = breadthFirstTraversal<VMServiceObjectNode>(
root,
returnCondition: (node) => node.object?.id == obj.id,
);
if (match != null) {
return match;
}
}
return null;
}
}
| devtools/packages/devtools_app/lib/src/screens/debugger/program_explorer_controller.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/debugger/program_explorer_controller.dart",
"repo_id": "devtools",
"token_count": 5235
} | 136 |
// Copyright 2019 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:devtools_app_shared/ui.dart';
import 'package:flutter/material.dart';
import '../../shared/analytics/analytics.dart' as ga;
import '../../shared/analytics/constants.dart' as gac;
import '../../shared/common_widgets.dart';
import '../../shared/primitives/blocking_action_mixin.dart';
import '../../shared/ui/tab.dart';
import 'inspector_controller.dart';
import 'inspector_screen.dart';
import 'layout_explorer/layout_explorer.dart';
class InspectorDetails extends StatelessWidget {
const InspectorDetails({
required this.detailsTree,
required this.controller,
Key? key,
}) : super(key: key);
final Widget detailsTree;
final InspectorController controller;
@override
Widget build(BuildContext context) {
final tabs = [
(
tab: _buildTab(tabName: 'Layout Explorer'),
tabView: LayoutExplorerTab(controller: controller),
),
(
tab: _buildTab(
tabName: 'Widget Details Tree',
trailing: InspectorExpandCollapseButtons(controller: controller),
),
tabView: detailsTree,
),
];
return AnalyticsTabbedView(
tabs: tabs,
gaScreen: gac.inspector,
);
}
DevToolsTab _buildTab({required String tabName, Widget? trailing}) {
return DevToolsTab.create(
tabName: tabName,
gaPrefix: 'inspectorDetailsTab',
trailing: trailing,
);
}
}
class InspectorExpandCollapseButtons extends StatefulWidget {
const InspectorExpandCollapseButtons({
Key? key,
required this.controller,
}) : super(key: key);
final InspectorController controller;
@override
State<InspectorExpandCollapseButtons> createState() =>
_InspectorExpandCollapseButtonsState();
}
class _InspectorExpandCollapseButtonsState
extends State<InspectorExpandCollapseButtons> with BlockingActionMixin {
bool get enableButtons => !actionInProgress;
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.centerRight,
decoration: BoxDecoration(
border: Border(
left: defaultBorderSide(Theme.of(context)),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
child: GaDevToolsButton(
icon: Icons.unfold_more,
onPressed: enableButtons ? _onExpandClick : null,
label: 'Expand all',
minScreenWidthForTextBeforeScaling:
InspectorScreenBodyState.minScreenWidthForTextBeforeScaling,
gaScreen: gac.inspector,
gaSelection: gac.expandAll,
outlined: false,
),
),
const SizedBox(width: denseSpacing),
SizedBox(
child: GaDevToolsButton(
icon: Icons.unfold_less,
onPressed: enableButtons ? _onCollapseClick : null,
label: 'Collapse to selected',
minScreenWidthForTextBeforeScaling:
InspectorScreenBodyState.minScreenWidthForTextBeforeScaling,
gaScreen: gac.inspector,
gaSelection: gac.collapseAll,
outlined: false,
),
),
],
),
);
}
void _onExpandClick() {
unawaited(
blockWhileInProgress(() async {
ga.select(gac.inspector, gac.expandAll);
await widget.controller.expandAllNodesInDetailsTree();
}),
);
}
void _onCollapseClick() {
ga.select(
gac.inspector,
gac.collapseAll,
);
widget.controller.collapseDetailsToSelected();
}
}
| devtools/packages/devtools_app/lib/src/screens/inspector/inspector_screen_details_tab.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/inspector/inspector_screen_details_tab.dart",
"repo_id": "devtools",
"token_count": 1614
} | 137 |
// Copyright 2019 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:devtools_app_shared/ui.dart';
import 'package:flutter/material.dart';
import '../../shared/common_widgets.dart';
import '../../shared/console/console.dart';
import 'logging_controller.dart';
class LogDetails extends StatefulWidget {
const LogDetails({Key? key, required this.log}) : super(key: key);
final LogData? log;
@override
State<LogDetails> createState() => _LogDetailsState();
static const copyToClipboardButtonKey =
Key('log_details_copy_to_clipboard_button');
}
class _LogDetailsState extends State<LogDetails>
with SingleTickerProviderStateMixin {
String? _lastDetails;
late final ScrollController scrollController;
@override
void initState() {
super.initState();
scrollController = ScrollController();
unawaited(_computeLogDetails());
}
@override
void didUpdateWidget(LogDetails oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.log != oldWidget.log) {
unawaited(_computeLogDetails());
}
}
Future<void> _computeLogDetails() async {
if (widget.log?.needsComputing ?? false) {
await widget.log!.compute();
setState(() {});
}
}
@override
Widget build(BuildContext context) {
final log = widget.log;
// TODO(#1370): Handle showing flutter errors in a structured manner.
return Stack(
children: [
_buildSimpleLog(log),
if (log != null && log.needsComputing)
const CenteredCircularProgressIndicator(),
],
);
}
Widget _buildSimpleLog(LogData? log) {
final details = log?.details;
if (details != _lastDetails) {
if (scrollController.hasClients) {
// Make sure we change the scroll if the log details shown have changed.
scrollController.jumpTo(0);
}
_lastDetails = details;
}
return RoundedOutlinedBorder(
clip: true,
child: ConsoleFrame(
title: _LogDetailsHeader(log: log),
child: Padding(
padding: const EdgeInsets.all(denseSpacing),
child: Scrollbar(
child: SingleChildScrollView(
controller: scrollController,
child: SelectableText(
log?.prettyPrinted() ?? '',
textAlign: TextAlign.left,
),
),
),
),
),
);
}
}
class _LogDetailsHeader extends StatelessWidget {
const _LogDetailsHeader({required this.log});
final LogData? log;
@override
Widget build(BuildContext context) {
String? Function()? dataProvider;
if (log?.details != null && log!.details!.isNotEmpty) {
dataProvider = log!.prettyPrinted;
}
return AreaPaneHeader(
title: const Text('Details'),
includeTopBorder: false,
roundedTopBorder: false,
actions: [
CopyToClipboardControl(
dataProvider: dataProvider,
buttonKey: LogDetails.copyToClipboardButtonKey,
),
],
);
}
}
| devtools/packages/devtools_app/lib/src/screens/logging/_log_details.dart/0 | {
"file_path": "devtools/packages/devtools_app/lib/src/screens/logging/_log_details.dart",
"repo_id": "devtools",
"token_count": 1214
} | 138 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.