text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame/events.dart';
import 'package:flutter/material.dart';
import '../brick_breaker.dart';
class Bat extends PositionComponent
with DragCallbacks, HasGameReference<BrickBreaker> {
Bat({
required this.cornerRadius,
required super.position,
required super.size,
}) : super(
anchor: Anchor.center,
children: [RectangleHitbox()],
);
final Radius cornerRadius;
final _paint = Paint()
..color = const Color(0xff1e6091)
..style = PaintingStyle.fill;
@override
void render(Canvas canvas) {
super.render(canvas);
canvas.drawRRect(
RRect.fromRectAndRadius(
Offset.zero & size.toSize(),
cornerRadius,
),
_paint);
}
@override
void onDragUpdate(DragUpdateEvent event) {
super.onDragUpdate(event);
position.x = (position.x + event.localDelta.x).clamp(0, game.width);
}
void moveBy(double dx) {
add(MoveToEffect(
Vector2((position.x + dx).clamp(0, game.width), position.y),
EffectController(duration: 0.1),
));
}
}
| codelabs/brick_breaker/step_07/lib/src/components/bat.dart/0 | {
"file_path": "codelabs/brick_breaker/step_07/lib/src/components/bat.dart",
"repo_id": "codelabs",
"token_count": 479
} | 20 |
#import "GeneratedPluginRegistrant.h"
| codelabs/brick_breaker/step_08/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/brick_breaker/step_08/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 21 |
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../brick_breaker.dart';
import '../config.dart';
class GameApp extends StatelessWidget {
const GameApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
textTheme: GoogleFonts.pressStart2pTextTheme().apply(
bodyColor: const Color(0xff184e77),
displayColor: const Color(0xff184e77),
),
),
home: Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xffa9d6e5),
Color(0xfff2e8cf),
],
),
),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: Center(
child: FittedBox(
child: SizedBox(
width: gameWidth,
height: gameHeight,
child: GameWidget.controlled(
gameFactory: BrickBreaker.new,
overlayBuilderMap: {
PlayState.welcome.name: (context, game) => Center(
child: Text(
'TAP TO PLAY',
style:
Theme.of(context).textTheme.headlineLarge,
),
),
PlayState.gameOver.name: (context, game) => Center(
child: Text(
'G A M E O V E R',
style:
Theme.of(context).textTheme.headlineLarge,
),
),
PlayState.won.name: (context, game) => Center(
child: Text(
'Y O U W O N ! ! !',
style:
Theme.of(context).textTheme.headlineLarge,
),
),
},
),
),
),
),
),
),
),
),
);
}
}
| codelabs/brick_breaker/step_09/lib/src/widgets/game_app.dart/0 | {
"file_path": "codelabs/brick_breaker/step_09/lib/src/widgets/game_app.dart",
"repo_id": "codelabs",
"token_count": 1624
} | 22 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/brick_breaker/step_09/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/brick_breaker/step_09/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 23 |
import 'dart:async';
import 'dart:math' as math;
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'components/components.dart';
import 'config.dart';
enum PlayState { welcome, playing, gameOver, won }
class BrickBreaker extends FlameGame
with HasCollisionDetection, KeyboardEvents, TapDetector {
BrickBreaker()
: super(
camera: CameraComponent.withFixedResolution(
width: gameWidth,
height: gameHeight,
),
);
final ValueNotifier<int> score = ValueNotifier(0);
final rand = math.Random();
double get width => size.x;
double get height => size.y;
late PlayState _playState;
PlayState get playState => _playState;
set playState(PlayState playState) {
_playState = playState;
switch (playState) {
case PlayState.welcome:
case PlayState.gameOver:
case PlayState.won:
overlays.add(playState.name);
case PlayState.playing:
overlays.remove(PlayState.welcome.name);
overlays.remove(PlayState.gameOver.name);
overlays.remove(PlayState.won.name);
}
}
@override
FutureOr<void> onLoad() async {
super.onLoad();
camera.viewfinder.anchor = Anchor.topLeft;
world.add(PlayArea());
playState = PlayState.welcome;
}
void startGame() {
if (playState == PlayState.playing) return;
world.removeAll(world.children.query<Ball>());
world.removeAll(world.children.query<Bat>());
world.removeAll(world.children.query<Brick>());
playState = PlayState.playing;
score.value = 0;
world.add(Ball(
difficultyModifier: difficultyModifier,
radius: ballRadius,
position: size / 2,
velocity: Vector2((rand.nextDouble() - 0.5) * width, height * 0.2)
.normalized()
..scale(height / 4)));
world.add(Bat(
size: Vector2(batWidth, batHeight),
cornerRadius: const Radius.circular(ballRadius / 2),
position: Vector2(width / 2, height * 0.95)));
world.addAll([
for (var i = 0; i < brickColors.length; i++)
for (var j = 1; j <= 5; j++)
Brick(
position: Vector2(
(i + 0.5) * brickWidth + (i + 1) * brickGutter,
(j + 2.0) * brickHeight + j * brickGutter,
),
color: brickColors[i],
),
]);
}
@override
void onTap() {
super.onTap();
startGame();
}
@override
KeyEventResult onKeyEvent(
KeyEvent event, Set<LogicalKeyboardKey> keysPressed) {
super.onKeyEvent(event, keysPressed);
switch (event.logicalKey) {
case LogicalKeyboardKey.arrowLeft:
world.children.query<Bat>().first.moveBy(-batStep);
case LogicalKeyboardKey.arrowRight:
world.children.query<Bat>().first.moveBy(batStep);
case LogicalKeyboardKey.space:
case LogicalKeyboardKey.enter:
startGame();
}
return KeyEventResult.handled;
}
@override
Color backgroundColor() => const Color(0xfff2e8cf);
}
| codelabs/brick_breaker/step_10/lib/src/brick_breaker.dart/0 | {
"file_path": "codelabs/brick_breaker/step_10/lib/src/brick_breaker.dart",
"repo_id": "codelabs",
"token_count": 1307
} | 24 |
#include "Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_04/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_04/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 25 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_05/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_05/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 26 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/dart-patterns-and-records/step_06_a/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_06_a/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 27 |
#include "Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_10/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_10/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 28 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_11_a/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_11_a/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 29 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/dart-patterns-and-records/step_11_b/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_11_b/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 30 |
// 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 'data.dart';
void main() {
runApp(const DocumentApp());
}
String formatDate(DateTime dateTime) {
final today = DateTime.now();
final difference = dateTime.difference(today);
return switch (difference) {
Duration(inDays: 0) => 'today',
Duration(inDays: 1) => 'tomorrow',
Duration(inDays: -1) => 'yesterday',
Duration(inDays: final days) when days > 7 => '${days ~/ 7} weeks from now',
Duration(inDays: final days) when days < -7 =>
'${days.abs() ~/ 7} weeks ago',
Duration(inDays: final days, isNegative: true) => '${days.abs()} days ago',
Duration(inDays: final days) => '$days days from now',
};
}
class DocumentApp extends StatelessWidget {
const DocumentApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: DocumentScreen(
document: Document(),
),
);
}
}
class DocumentScreen extends StatelessWidget {
final Document document;
const DocumentScreen({
required this.document,
super.key,
});
@override
Widget build(BuildContext context) {
final (title, :modified) = document.metadata;
final formattedModifiedDate = formatDate(modified);
final blocks = document.getBlocks();
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Column(
children: [
Text('Last modified: $formattedModifiedDate'),
Expanded(
child: ListView.builder(
itemCount: blocks.length,
itemBuilder: (context, index) {
return BlockWidget(block: blocks[index]);
},
),
),
],
),
);
}
}
class BlockWidget extends StatelessWidget {
final Block block;
const BlockWidget({
required this.block,
super.key,
});
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all(8),
child: switch (block) {
HeaderBlock(:final text) => Text(
text,
style: Theme.of(context).textTheme.displayMedium,
),
ParagraphBlock(:final text) => Text(text),
CheckboxBlock(:final text, :final isChecked) => Row(
children: [
Checkbox(value: isChecked, onChanged: (_) {}),
Text(text),
],
),
},
);
}
}
| codelabs/dart-patterns-and-records/step_12/lib/main.dart/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_12/lib/main.dart",
"repo_id": "codelabs",
"token_count": 1059
} | 31 |
# DartPad workshops
To refocus on its core use cases,
DartPad no longer supports the step-by-step workshops
previously maintained in this directory.
To learn more about this change, check out the
[DartPad redesign announcement][].
> [!TIP]
> For other great Flutter learning resources and experiences,
> consider trying a [Flutter codelab][].
[DartPad redesign announcement]: https://github.com/dart-lang/dart-pad/issues/2808
[Flutter codelab]: https://docs.flutter.dev/codelabs
| codelabs/dartpad_codelabs/README.md/0 | {
"file_path": "codelabs/dartpad_codelabs/README.md",
"repo_id": "codelabs",
"token_count": 140
} | 32 |
#import "GeneratedPluginRegistrant.h"
| codelabs/ffigen_codelab/step_05/example/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/ffigen_codelab/step_05/example/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 33 |
// 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:ffi';
import 'dart:io' show Platform;
import 'package:ffi/ffi.dart' as ffi;
import 'duktape_bindings_generated.dart';
const String _libName = 'ffigen_app';
/// The dynamic library in which the symbols for [DuktapeBindings] can be found.
final DynamicLibrary _dylib = () {
if (Platform.isMacOS || Platform.isIOS) {
return DynamicLibrary.open('$_libName.framework/$_libName');
}
if (Platform.isAndroid || Platform.isLinux) {
return DynamicLibrary.open('lib$_libName.so');
}
if (Platform.isWindows) {
return DynamicLibrary.open('$_libName.dll');
}
throw UnsupportedError('Unknown platform: ${Platform.operatingSystem}');
}();
/// The bindings to the native functions in [_dylib].
final DuktapeBindings _bindings = DuktapeBindings(_dylib);
class Duktape {
Duktape() {
ctx =
_bindings.duk_create_heap(nullptr, nullptr, nullptr, nullptr, nullptr);
}
void evalString(String jsCode) {
// From duktape.h:
// #define duk_peval_string(ctx,src) \
// (duk_eval_raw((ctx), (src), 0, 0 /*args*/ | DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN | DUK_COMPILE_NOFILENAME))
var nativeUtf8 = jsCode.toNativeUtf8();
_bindings.duk_eval_raw(
ctx,
nativeUtf8.cast<Char>(),
0,
0 /*args*/ |
DUK_COMPILE_EVAL |
DUK_COMPILE_SAFE |
DUK_COMPILE_NOSOURCE |
DUK_COMPILE_STRLEN |
DUK_COMPILE_NOFILENAME);
ffi.malloc.free(nativeUtf8);
}
int getInt(int index) {
return _bindings.duk_get_int(ctx, index);
}
void dispose() {
_bindings.duk_destroy_heap(ctx);
ctx = nullptr;
}
late Pointer<duk_hthread> ctx;
}
| codelabs/ffigen_codelab/step_05/lib/ffigen_app.dart/0 | {
"file_path": "codelabs/ffigen_codelab/step_05/lib/ffigen_app.dart",
"repo_id": "codelabs",
"token_count": 799
} | 34 |
#import "GeneratedPluginRegistrant.h"
| codelabs/ffigen_codelab/step_07/example/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/ffigen_codelab/step_07/example/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 35 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/firebase-auth-flutterfire-ui/complete/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/firebase-auth-flutterfire-ui/complete/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 36 |
{
"projects": {
"default": "flutterfire-ui-codelab"
}
}
| codelabs/firebase-auth-flutterfire-ui/start/.firebaserc/0 | {
"file_path": "codelabs/firebase-auth-flutterfire-ui/start/.firebaserc",
"repo_id": "codelabs",
"token_count": 31
} | 37 |
<?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>CLIENT_ID</key>
<string>963656261848-v7r3vq1v6haupv0l1mdrmsf56ktnua60.apps.googleusercontent.com</string>
<key>REVERSED_CLIENT_ID</key>
<string>com.googleusercontent.apps.963656261848-v7r3vq1v6haupv0l1mdrmsf56ktnua60</string>
<key>API_KEY</key>
<string>AIzaSyBqLWsqFjYAdGyihKTahMRDQMo0N6NVjAs</string>
<key>GCM_SENDER_ID</key>
<string>963656261848</string>
<key>PLIST_VERSION</key>
<string>1</string>
<key>BUNDLE_ID</key>
<string>com.example.complete</string>
<key>PROJECT_ID</key>
<string>flutterfire-ui-codelab</string>
<key>STORAGE_BUCKET</key>
<string>flutterfire-ui-codelab.appspot.com</string>
<key>IS_ADS_ENABLED</key>
<false></false>
<key>IS_ANALYTICS_ENABLED</key>
<false></false>
<key>IS_APPINVITE_ENABLED</key>
<true></true>
<key>IS_GCM_ENABLED</key>
<true></true>
<key>IS_SIGNIN_ENABLED</key>
<true></true>
<key>GOOGLE_APP_ID</key>
<string>1:963656261848:ios:d9e01cfe8b675dfcb237ad</string>
</dict>
</plist>
| codelabs/firebase-auth-flutterfire-ui/start/ios/Runner/GoogleService-Info.plist/0 | {
"file_path": "codelabs/firebase-auth-flutterfire-ui/start/ios/Runner/GoogleService-Info.plist",
"repo_id": "codelabs",
"token_count": 564
} | 38 |
{
"projects": {
"default": "flutter-firebase-codelab-d6b79"
}
}
| codelabs/firebase-emulator-suite/complete/.firebaserc/0 | {
"file_path": "codelabs/firebase-emulator-suite/complete/.firebaserc",
"repo_id": "codelabs",
"token_count": 36
} | 39 |
// 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:google_fonts/google_fonts.dart';
import 'home_page.dart';
void main() {
runApp(const App());
}
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Firebase Meetup',
theme: ThemeData(
buttonTheme: Theme.of(context).buttonTheme.copyWith(
highlightColor: Colors.deepPurple,
),
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
textTheme: GoogleFonts.robotoTextTheme(
Theme.of(context).textTheme,
),
visualDensity: VisualDensity.adaptivePlatformDensity,
useMaterial3: true,
),
home: const HomePage(),
);
}
}
| codelabs/firebase-get-to-know-flutter/step_04/lib/main.dart/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_04/lib/main.dart",
"repo_id": "codelabs",
"token_count": 368
} | 40 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/firebase-get-to-know-flutter/step_06/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_06/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 41 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/firebase-get-to-know-flutter/step_09/android/gradle.properties/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_09/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 42 |
// 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:firebase_auth/firebase_auth.dart'
hide EmailAuthProvider, PhoneAuthProvider;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'app_state.dart';
import 'guest_book.dart';
import 'src/authentication.dart';
import 'src/widgets.dart';
import 'yes_no_selection.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Firebase Meetup'),
),
body: ListView(
children: <Widget>[
Image.asset('assets/codelab.png'),
const SizedBox(height: 8),
Consumer<ApplicationState>(
builder: (context, appState, _) =>
IconAndDetail(Icons.calendar_today, appState.eventDate),
),
const IconAndDetail(Icons.location_city, 'San Francisco'),
Consumer<ApplicationState>(
builder: (context, appState, _) => AuthFunc(
loggedIn: appState.loggedIn,
signOut: () {
FirebaseAuth.instance.signOut();
},
enableFreeSwag: appState.enableFreeSwag,
),
),
const Divider(
height: 8,
thickness: 1,
indent: 8,
endIndent: 8,
color: Colors.grey,
),
const Header("What we'll be doing"),
Consumer<ApplicationState>(
builder: (context, appState, _) => Paragraph(
appState.callToAction,
),
),
Consumer<ApplicationState>(
builder: (context, appState, _) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
switch (appState.attendees) {
1 => const Paragraph('1 person going'),
>= 2 => Paragraph('${appState.attendees} people going'),
_ => const Paragraph('No one going'),
},
if (appState.loggedIn) ...[
YesNoSelection(
state: appState.attending,
onSelection: (attending) => appState.attending = attending,
),
const Header('Discussion'),
GuestBook(
addMessage: (message) =>
appState.addMessageToGuestBook(message),
messages: appState.guestBookMessages,
),
],
],
),
),
],
),
);
}
}
| codelabs/firebase-get-to-know-flutter/step_09/lib/home_page.dart/0 | {
"file_path": "codelabs/firebase-get-to-know-flutter/step_09/lib/home_page.dart",
"repo_id": "codelabs",
"token_count": 1396
} | 43 |
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <url_launcher_linux/url_launcher_plugin.h>
#include <window_to_front/window_to_front_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
g_autoptr(FlPluginRegistrar) window_to_front_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "WindowToFrontPlugin");
window_to_front_plugin_register_with_registrar(window_to_front_registrar);
}
| codelabs/github-client/step_06/linux/flutter/generated_plugin_registrant.cc/0 | {
"file_path": "codelabs/github-client/step_06/linux/flutter/generated_plugin_registrant.cc",
"repo_id": "codelabs",
"token_count": 267
} | 44 |
#ifndef FLUTTER_PLUGIN_WINDOW_TO_FRONT_PLUGIN_H_
#define FLUTTER_PLUGIN_WINDOW_TO_FRONT_PLUGIN_H_
#include <flutter_linux/flutter_linux.h>
G_BEGIN_DECLS
#ifdef FLUTTER_PLUGIN_IMPL
#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default")))
#else
#define FLUTTER_PLUGIN_EXPORT
#endif
typedef struct _WindowToFrontPlugin WindowToFrontPlugin;
typedef struct {
GObjectClass parent_class;
} WindowToFrontPluginClass;
FLUTTER_PLUGIN_EXPORT GType window_to_front_plugin_get_type();
FLUTTER_PLUGIN_EXPORT void window_to_front_plugin_register_with_registrar(
FlPluginRegistrar* registrar);
G_END_DECLS
#endif // FLUTTER_PLUGIN_WINDOW_TO_FRONT_PLUGIN_H_
| codelabs/github-client/window_to_front/linux/include/window_to_front/window_to_front_plugin.h/0 | {
"file_path": "codelabs/github-client/window_to_front/linux/include/window_to_front/window_to_front_plugin.h",
"repo_id": "codelabs",
"token_count": 278
} | 45 |
include: ../../analysis_options.yaml
analyzer:
exclude:
- lib/src/*.g.dart
| codelabs/google-maps-in-flutter/step_3/analysis_options.yaml/0 | {
"file_path": "codelabs/google-maps-in-flutter/step_3/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 36
} | 46 |
package com.example.haiku_generator
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| codelabs/haiku_generator/finished/android/app/src/main/kotlin/com/example/haiku_generator/MainActivity.kt/0 | {
"file_path": "codelabs/haiku_generator/finished/android/app/src/main/kotlin/com/example/haiku_generator/MainActivity.kt",
"repo_id": "codelabs",
"token_count": 40
} | 47 |
import 'package:flutter/material.dart';
import 'shimmer_gradient.dart';
import 'shimmer_loading.dart';
class ShimmerLoadingAnim extends StatelessWidget {
const ShimmerLoadingAnim(
{super.key, required this.child, this.isLoading = false});
final Widget child;
final bool isLoading;
@override
Widget build(BuildContext context) {
return Shimmer(
linearGradient: shimmerGradient,
child: ShimmerLoading(
isLoading: isLoading,
child: child,
),
);
}
}
| codelabs/haiku_generator/finished/lib/widgets/shimmer_loading_anim.dart/0 | {
"file_path": "codelabs/haiku_generator/finished/lib/widgets/shimmer_loading_anim.dart",
"repo_id": "codelabs",
"token_count": 186
} | 48 |
import '../../domain/repositories/abstract/poem_repository.dart';
// ignore: unused_import
import 'dart:convert';
// ignore: unused_import
import 'package:http/http.dart' as http;
class PoemRepositoryImpl implements PoemRepository {
PoemRepositoryImpl();
@override
Future<String> getPoems(String productName) async {
return "";
}
}
| codelabs/haiku_generator/step0/lib/data/repositories/poem_repository_impl.dart/0 | {
"file_path": "codelabs/haiku_generator/step0/lib/data/repositories/poem_repository_impl.dart",
"repo_id": "codelabs",
"token_count": 118
} | 49 |
import 'package:flutter/material.dart';
import 'article_screen.dart';
import 'news_data.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Top Stories'),
centerTitle: false,
titleTextStyle: const TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: Colors.black)),
body: ListView.separated(
separatorBuilder: (context, idx) {
return const Divider();
},
itemCount: getNewsStories().length,
itemBuilder: (context, idx) {
final article = getNewsStories()[idx];
return ListTile(
key: Key('$idx ${article.hashCode}'),
title: Text(article.title),
subtitle: Text(article.description),
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<ArticleScreen>(
builder: (context) {
return ArticleScreen(article: article);
},
),
);
},
);
},
));
}
}
| codelabs/homescreen_codelab/step_03/lib/home_screen.dart/0 | {
"file_path": "codelabs/homescreen_codelab/step_03/lib/home_screen.dart",
"repo_id": "codelabs",
"token_count": 712
} | 50 |
import WidgetKit
import SwiftUI
@main
struct NewsWidgetsBundle: WidgetBundle {
var body: some Widget {
NewsWidgets()
}
}
| codelabs/homescreen_codelab/step_05/ios/NewsWidgets/NewsWidgetsBundle.swift/0 | {
"file_path": "codelabs/homescreen_codelab/step_05/ios/NewsWidgets/NewsWidgetsBundle.swift",
"repo_id": "codelabs",
"token_count": 58
} | 51 |
<resources>
<style name="Widget.Android.AppWidget.Container" parent="android:Widget">
<item name="android:id">@android:id/background</item>
<item name="android:padding">?attr/appWidgetPadding</item>
<item name="android:background">@drawable/app_widget_background</item>
</style>
<style name="Widget.Android.AppWidget.InnerView" parent="android:Widget">
<item name="android:padding">?attr/appWidgetPadding</item>
<item name="android:background">@drawable/app_widget_inner_view_background</item>
<item name="android:textColor">?android:attr/textColorPrimary</item>
</style>
</resources> | codelabs/homescreen_codelab/step_06/android/app/src/main/res/values-v21/styles.xml/0 | {
"file_path": "codelabs/homescreen_codelab/step_06/android/app/src/main/res/values-v21/styles.xml",
"repo_id": "codelabs",
"token_count": 234
} | 52 |
import 'package:flutter/material.dart';
// New: import the home_widget package.
import 'package:home_widget/home_widget.dart';
import 'home_screen.dart';
import 'news_data.dart';
class ArticleScreen extends StatefulWidget {
final NewsArticle article;
const ArticleScreen({
super.key,
required this.article,
});
@override
State<ArticleScreen> createState() => _ArticleScreenState();
}
class _ArticleScreenState extends State<ArticleScreen> {
// New: add this GlobalKey
final _globalKey = GlobalKey();
// New: add this imagePath
String? imagePath;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.article.title),
),
// New: add this FloatingActionButton
floatingActionButton: FloatingActionButton.extended(
onPressed: () async {
if (_globalKey.currentContext != null) {
var path = await HomeWidget.renderFlutterWidget(
const LineChart(),
key: 'filename',
logicalSize: _globalKey.currentContext!.size!,
pixelRatio:
MediaQuery.of(_globalKey.currentContext!).devicePixelRatio,
) as String;
setState(() {
imagePath = path;
});
}
updateHeadline(widget.article);
},
label: const Text('Update Homescreen'),
),
body: ListView(
padding: const EdgeInsets.all(16.0),
children: [
Text(
widget.article.description,
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 20.0),
Text(widget.article.articleText!),
const SizedBox(height: 20.0),
Center(
// New: Add this key
key: _globalKey,
child: const LineChart(),
),
const SizedBox(height: 20.0),
Text(widget.article.articleText!),
],
),
);
}
}
class LineChart extends StatelessWidget {
const LineChart({
super.key,
});
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: LineChartPainter(),
child: const SizedBox(
height: 200,
width: 200,
),
);
}
}
class LineChartPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final axisPaint = Paint()
..color = Colors.black
..strokeWidth = 2
..style = PaintingStyle.stroke;
final dataPaint = Paint()
..color = Colors.blue
..strokeWidth = 2
..style = PaintingStyle.stroke;
final markingLinePaint = Paint()
..color = Colors.red
..strokeWidth = 2
..style = PaintingStyle.stroke;
final mockDataPoints = [
const Offset(15, 155),
const Offset(20, 133),
const Offset(34, 125),
const Offset(40, 105),
const Offset(70, 85),
const Offset(80, 95),
const Offset(90, 60),
const Offset(120, 54),
const Offset(160, 60),
const Offset(200, -10),
];
final axis = Path()
..moveTo(0, 0)
..lineTo(0, size.height)
..lineTo(size.width, size.height);
final markingLine = Path()
..moveTo(-10, 50)
..lineTo(size.width + 10, 50);
final data = Path()..moveTo(1, 180);
for (var dataPoint in mockDataPoints) {
data.lineTo(dataPoint.dx, dataPoint.dy);
}
canvas.drawPath(axis, axisPaint);
canvas.drawPath(data, dataPaint);
canvas.drawPath(markingLine, markingLinePaint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => false;
}
| codelabs/homescreen_codelab/step_06/lib/article_screen.dart/0 | {
"file_path": "codelabs/homescreen_codelab/step_06/lib/article_screen.dart",
"repo_id": "codelabs",
"token_count": 1567
} | 53 |
enum FirebaseState {
loading,
available,
notAvailable,
}
| codelabs/in_app_purchases/complete/app/lib/model/firebase_state.dart/0 | {
"file_path": "codelabs/in_app_purchases/complete/app/lib/model/firebase_state.dart",
"repo_id": "codelabs",
"token_count": 21
} | 54 |
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:app_store_server_sdk/app_store_server_sdk.dart';
import 'package:firebase_backend_dart/app_store_purchase_handler.dart';
import 'package:firebase_backend_dart/constants.dart';
import 'package:firebase_backend_dart/google_play_purchase_handler.dart';
import 'package:firebase_backend_dart/helpers.dart';
import 'package:firebase_backend_dart/iap_repository.dart';
import 'package:firebase_backend_dart/products.dart';
import 'package:firebase_backend_dart/purchase_handler.dart';
import 'package:googleapis/androidpublisher/v3.dart' as ap;
import 'package:googleapis/firestore/v1.dart' as fs;
import 'package:googleapis/pubsub/v1.dart' as pubsub;
import 'package:googleapis_auth/auth_io.dart' as auth;
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
/// Creates the Google Play and Apple Store [PurchaseHandler]
/// and their dependencies
Future<Map<String, PurchaseHandler>> _createPurchaseHandlers() async {
// Configure Android Publisher API access
final serviceAccountGooglePlay =
File('assets/service-account-google-play.json').readAsStringSync();
final clientCredentialsGooglePlay =
auth.ServiceAccountCredentials.fromJson(serviceAccountGooglePlay);
final clientGooglePlay =
await auth.clientViaServiceAccount(clientCredentialsGooglePlay, [
ap.AndroidPublisherApi.androidpublisherScope,
pubsub.PubsubApi.cloudPlatformScope,
]);
final androidPublisher = ap.AndroidPublisherApi(clientGooglePlay);
// Pub/Sub API to receive on purchase events from Google Play
final pubsubApi = pubsub.PubsubApi(clientGooglePlay);
// Configure Firestore API access
final serviceAccountFirebase =
File('assets/service-account-firebase.json').readAsStringSync();
final clientCredentialsFirebase =
auth.ServiceAccountCredentials.fromJson(serviceAccountFirebase);
final clientFirebase =
await auth.clientViaServiceAccount(clientCredentialsFirebase, [
fs.FirestoreApi.cloudPlatformScope,
]);
final firestoreApi = fs.FirestoreApi(clientFirebase);
final dynamic json = jsonDecode(serviceAccountFirebase);
final projectId = json['project_id'] as String;
final iapRepository = IapRepository(firestoreApi, projectId);
final subscriptionKeyAppStore =
File('assets/SubscriptionKey.p8').readAsStringSync();
// Configure Apple Store API access
var appStoreEnvironment = AppStoreEnvironment.sandbox(
bundleId: bundleId,
issuerId: appStoreIssuerId,
keyId: appStoreKeyId,
privateKey: subscriptionKeyAppStore,
);
// Stored token for Apple Store API access, if available
final file = File('assets/appstore.token');
String? appStoreToken;
if (file.existsSync() && file.lengthSync() > 0) {
appStoreToken = file.readAsStringSync();
}
final appStoreServerAPI = AppStoreServerAPI(
AppStoreServerHttpClient(
appStoreEnvironment,
jwt: appStoreToken,
jwtTokenUpdatedCallback: (token) {
file.writeAsStringSync(token);
},
),
);
return {
'google_play': GooglePlayPurchaseHandler(
androidPublisher,
iapRepository,
pubsubApi,
),
'app_store': AppStorePurchaseHandler(
iapRepository,
appStoreServerAPI,
),
};
}
Future<void> main() async {
final router = Router();
final purchaseHandlers = await _createPurchaseHandlers();
/// Warning: This endpoint has no security
/// and does not implement user authentication.
/// Production applications should implement authentication.
// ignore: avoid_types_on_closure_parameters
router.post('/verifypurchase', (Request request) async {
final dynamic payload = json.decode(await request.readAsString());
// NOTE: userId should be obtained using authentication methods.
// source from PurchaseDetails.verificationData.source
// productData product data based on the productId
// token from PurchaseDetails.verificationData.serverVerificationData
final (:userId, :source, :productData, :token) = getPurchaseData(payload);
// Will call to verifyPurchase on
// [GooglePlayPurchaseHandler] or [AppleStorePurchaseHandler]
final result = await purchaseHandlers[source]!.verifyPurchase(
userId: userId,
productData: productData,
token: token,
);
if (result) {
// Note: Better success response recommended
return Response.ok('all good!');
} else {
// Note: Better error handling recommended
return Response.internalServerError();
}
});
// Start service
await serveHandler(router.call);
}
({
String userId,
String source,
ProductData productData,
String token,
}) getPurchaseData(dynamic payload) {
if (payload
case {
'userId': String userId,
'source': String source,
'productId': String productId,
'verificationData': String token,
}) {
return (
userId: userId,
source: source,
productData: productDataMap[productId]!,
token: token,
);
} else {
throw const FormatException('Unexpected JSON');
}
}
| codelabs/in_app_purchases/complete/dart-backend/bin/server.dart/0 | {
"file_path": "codelabs/in_app_purchases/complete/dart-backend/bin/server.dart",
"repo_id": "codelabs",
"token_count": 1761
} | 55 |
package com.example.dashclicker
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| codelabs/in_app_purchases/step_00/app/android/app/src/main/kotlin/com/example/dashclicker/MainActivity.kt/0 | {
"file_path": "codelabs/in_app_purchases/step_00/app/android/app/src/main/kotlin/com/example/dashclicker/MainActivity.kt",
"repo_id": "codelabs",
"token_count": 38
} | 56 |
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../model/purchasable_product.dart';
import '../model/store_state.dart';
import 'dash_counter.dart';
class DashPurchases extends ChangeNotifier {
DashCounter counter;
StoreState storeState = StoreState.available;
List<PurchasableProduct> products = [
PurchasableProduct(
'Spring is in the air',
'Many dashes flying out from their nests',
'\$0.99',
),
PurchasableProduct(
'Jet engine',
'Doubles you clicks per second for a day',
'\$1.99',
),
];
bool get beautifiedDash => false;
DashPurchases(this.counter);
Future<void> buy(PurchasableProduct product) async {
product.status = ProductStatus.pending;
notifyListeners();
await Future<void>.delayed(const Duration(seconds: 5));
product.status = ProductStatus.purchased;
notifyListeners();
await Future<void>.delayed(const Duration(seconds: 5));
product.status = ProductStatus.purchasable;
notifyListeners();
}
}
| codelabs/in_app_purchases/step_00/app/lib/logic/dash_purchases.dart/0 | {
"file_path": "codelabs/in_app_purchases/step_00/app/lib/logic/dash_purchases.dart",
"repo_id": "codelabs",
"token_count": 382
} | 57 |
## 1.0.0
- Initial version.
| codelabs/in_app_purchases/step_00/dart-backend/CHANGELOG.md/0 | {
"file_path": "codelabs/in_app_purchases/step_00/dart-backend/CHANGELOG.md",
"repo_id": "codelabs",
"token_count": 13
} | 58 |
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import '../main.dart';
import '../model/purchasable_product.dart';
import '../model/store_state.dart';
import 'dash_counter.dart';
class DashPurchases extends ChangeNotifier {
DashCounter counter;
StoreState storeState = StoreState.notAvailable;
late StreamSubscription<List<PurchaseDetails>> _subscription;
List<PurchasableProduct> products = [
PurchasableProduct(
'Spring is in the air',
'Many dashes flying out from their nests',
'\$0.99',
),
PurchasableProduct(
'Jet engine',
'Doubles you clicks per second for a day',
'\$1.99',
),
];
bool get beautifiedDash => false;
final iapConnection = IAPConnection.instance;
DashPurchases(this.counter) {
final purchaseUpdated = iapConnection.purchaseStream;
_subscription = purchaseUpdated.listen(
_onPurchaseUpdate,
onDone: _updateStreamOnDone,
onError: _updateStreamOnError,
);
}
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
Future<void> buy(PurchasableProduct product) async {
product.status = ProductStatus.pending;
notifyListeners();
await Future<void>.delayed(const Duration(seconds: 5));
product.status = ProductStatus.purchased;
notifyListeners();
await Future<void>.delayed(const Duration(seconds: 5));
product.status = ProductStatus.purchasable;
notifyListeners();
}
void _onPurchaseUpdate(List<PurchaseDetails> purchaseDetailsList) {
// Handle purchases here
}
void _updateStreamOnDone() {
_subscription.cancel();
}
void _updateStreamOnError(dynamic error) {
//Handle error here
}
}
| codelabs/in_app_purchases/step_07/app/lib/logic/dash_purchases.dart/0 | {
"file_path": "codelabs/in_app_purchases/step_07/app/lib/logic/dash_purchases.dart",
"repo_id": "codelabs",
"token_count": 635
} | 59 |
## 1.0.0
- Initial version.
| codelabs/in_app_purchases/step_07/dart-backend/CHANGELOG.md/0 | {
"file_path": "codelabs/in_app_purchases/step_07/dart-backend/CHANGELOG.md",
"repo_id": "codelabs",
"token_count": 13
} | 60 |
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import '../constants.dart';
import '../main.dart';
import '../model/purchasable_product.dart';
import '../model/store_state.dart';
import 'dash_counter.dart';
class DashPurchases extends ChangeNotifier {
DashCounter counter;
StoreState storeState = StoreState.loading;
late StreamSubscription<List<PurchaseDetails>> _subscription;
List<PurchasableProduct> products = [];
bool get beautifiedDash => _beautifiedDashUpgrade;
bool _beautifiedDashUpgrade = false;
final iapConnection = IAPConnection.instance;
DashPurchases(this.counter) {
final purchaseUpdated = iapConnection.purchaseStream;
_subscription = purchaseUpdated.listen(
_onPurchaseUpdate,
onDone: _updateStreamOnDone,
onError: _updateStreamOnError,
);
loadPurchases();
}
Future<void> loadPurchases() async {
final available = await iapConnection.isAvailable();
if (!available) {
storeState = StoreState.notAvailable;
notifyListeners();
return;
}
const ids = <String>{
storeKeyConsumable,
storeKeySubscription,
storeKeyUpgrade,
};
final response = await iapConnection.queryProductDetails(ids);
products =
response.productDetails.map((e) => PurchasableProduct(e)).toList();
storeState = StoreState.available;
notifyListeners();
}
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
Future<void> buy(PurchasableProduct product) async {
final purchaseParam = PurchaseParam(productDetails: product.productDetails);
switch (product.id) {
case storeKeyConsumable:
await iapConnection.buyConsumable(purchaseParam: purchaseParam);
case storeKeySubscription:
case storeKeyUpgrade:
await iapConnection.buyNonConsumable(purchaseParam: purchaseParam);
default:
throw ArgumentError.value(
product.productDetails, '${product.id} is not a known product');
}
}
Future<void> _onPurchaseUpdate(
List<PurchaseDetails> purchaseDetailsList) async {
for (var purchaseDetails in purchaseDetailsList) {
await _handlePurchase(purchaseDetails);
}
notifyListeners();
}
Future<void> _handlePurchase(PurchaseDetails purchaseDetails) async {
if (purchaseDetails.status == PurchaseStatus.purchased) {
switch (purchaseDetails.productID) {
case storeKeySubscription:
counter.applyPaidMultiplier();
case storeKeyConsumable:
counter.addBoughtDashes(2000);
case storeKeyUpgrade:
_beautifiedDashUpgrade = true;
}
}
if (purchaseDetails.pendingCompletePurchase) {
await iapConnection.completePurchase(purchaseDetails);
}
}
void _updateStreamOnDone() {
_subscription.cancel();
}
void _updateStreamOnError(dynamic error) {
//Handle error here
}
}
| codelabs/in_app_purchases/step_08/app/lib/logic/dash_purchases.dart/0 | {
"file_path": "codelabs/in_app_purchases/step_08/app/lib/logic/dash_purchases.dart",
"repo_id": "codelabs",
"token_count": 1072
} | 61 |
## 1.0.0
- Initial version.
| codelabs/in_app_purchases/step_08/dart-backend/CHANGELOG.md/0 | {
"file_path": "codelabs/in_app_purchases/step_08/dart-backend/CHANGELOG.md",
"repo_id": "codelabs",
"token_count": 13
} | 62 |
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:in_app_purchase/in_app_purchase.dart';
import '../constants.dart';
import '../main.dart';
import '../model/purchasable_product.dart';
import '../model/store_state.dart';
import 'dash_counter.dart';
import 'firebase_notifier.dart';
class DashPurchases extends ChangeNotifier {
DashCounter counter;
FirebaseNotifier firebaseNotifier;
StoreState storeState = StoreState.loading;
late StreamSubscription<List<PurchaseDetails>> _subscription;
List<PurchasableProduct> products = [];
bool get beautifiedDash => _beautifiedDashUpgrade;
bool _beautifiedDashUpgrade = false;
final iapConnection = IAPConnection.instance;
DashPurchases(this.counter, this.firebaseNotifier) {
final purchaseUpdated = iapConnection.purchaseStream;
_subscription = purchaseUpdated.listen(
_onPurchaseUpdate,
onDone: _updateStreamOnDone,
onError: _updateStreamOnError,
);
loadPurchases();
}
Future<void> loadPurchases() async {
final available = await iapConnection.isAvailable();
if (!available) {
storeState = StoreState.notAvailable;
notifyListeners();
return;
}
const ids = <String>{
storeKeyConsumable,
storeKeySubscription,
storeKeyUpgrade,
};
final response = await iapConnection.queryProductDetails(ids);
products =
response.productDetails.map((e) => PurchasableProduct(e)).toList();
storeState = StoreState.available;
notifyListeners();
}
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
Future<void> buy(PurchasableProduct product) async {
final purchaseParam = PurchaseParam(productDetails: product.productDetails);
switch (product.id) {
case storeKeyConsumable:
await iapConnection.buyConsumable(purchaseParam: purchaseParam);
case storeKeySubscription:
case storeKeyUpgrade:
await iapConnection.buyNonConsumable(purchaseParam: purchaseParam);
default:
throw ArgumentError.value(
product.productDetails, '${product.id} is not a known product');
}
}
Future<void> _onPurchaseUpdate(
List<PurchaseDetails> purchaseDetailsList) async {
for (var purchaseDetails in purchaseDetailsList) {
await _handlePurchase(purchaseDetails);
}
notifyListeners();
}
Future<void> _handlePurchase(PurchaseDetails purchaseDetails) async {
if (purchaseDetails.status == PurchaseStatus.purchased) {
// Send to server
var validPurchase = await _verifyPurchase(purchaseDetails);
if (validPurchase) {
// Apply changes locally
switch (purchaseDetails.productID) {
case storeKeySubscription:
counter.applyPaidMultiplier();
case storeKeyConsumable:
counter.addBoughtDashes(2000);
case storeKeyUpgrade:
_beautifiedDashUpgrade = true;
}
}
}
if (purchaseDetails.pendingCompletePurchase) {
await iapConnection.completePurchase(purchaseDetails);
}
}
Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async {
final url = Uri.parse('http://$serverIp:8080/verifypurchase');
const headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
final response = await http.post(
url,
body: jsonEncode({
'source': purchaseDetails.verificationData.source,
'productId': purchaseDetails.productID,
'verificationData':
purchaseDetails.verificationData.serverVerificationData,
'userId': firebaseNotifier.user?.uid,
}),
headers: headers,
);
if (response.statusCode == 200) {
return true;
} else {
return false;
}
}
void _updateStreamOnDone() {
_subscription.cancel();
}
void _updateStreamOnError(dynamic error) {
//Handle error here
}
}
| codelabs/in_app_purchases/step_09/app/lib/logic/dash_purchases.dart/0 | {
"file_path": "codelabs/in_app_purchases/step_09/app/lib/logic/dash_purchases.dart",
"repo_id": "codelabs",
"token_count": 1489
} | 63 |
## 1.0.0
- Initial version.
| codelabs/in_app_purchases/step_09/dart-backend/CHANGELOG.md/0 | {
"file_path": "codelabs/in_app_purchases/step_09/dart-backend/CHANGELOG.md",
"repo_id": "codelabs",
"token_count": 13
} | 64 |
name: Your first Flutter app (updated for 2023)
steps:
- name: step_03
steps:
- name: Remove generated code
rmdir: step_03
- name: Create project
flutter: create namer_app
- name: Strip DEVELOPMENT_TEAM
strip-lines-containing: DEVELOPMENT_TEAM =
path: namer_app/ios/Runner.xcodeproj/project.pbxproj
- name: Replace pubspec.yaml
path: namer_app/pubspec.yaml
replace-contents: |
name: namer_app
description: A new Flutter project.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 0.0.1+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
english_words: ^4.0.0
provider: ^6.0.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
flutter:
uses-material-design: true
- name: Update dependencies
path: namer_app
flutter: pub upgrade --major-versions
- name: Replace analysis_options.yaml
path: namer_app/analysis_options.yaml
replace-contents: |
include: package:flutter_lints/flutter.yaml
linter:
rules:
avoid_print: false
prefer_const_constructors_in_immutables: false
prefer_const_constructors: false
prefer_const_literals_to_create_immutables: false
prefer_final_fields: false
unnecessary_breaks: true
use_key_in_widget_constructors: false
- name: Replace lib/main.dart
path: namer_app/lib/main.dart
replace-contents: |
import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => MyAppState(),
child: MaterialApp(
title: 'Namer App',
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange),
),
home: MyHomePage(),
),
);
}
}
class MyAppState extends ChangeNotifier {
var current = WordPair.random();
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
var appState = context.watch<MyAppState>();
return Scaffold(
body: Column(
children: [
Text('A random idea:'),
Text(appState.current.asLowerCase),
],
),
);
}
}
- name: Remove README
rm: namer_app/README.md
- name: Replace test/widget_test.dart
path: namer_app/test/widget_test.dart
replace-contents: |
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 idea:'), findsOneWidget);
});
}
- name: Build iOS simulator bundle
platforms: [ macos ]
path: namer_app
flutter: build ios --simulator
- name: Build macOS app
platforms: [ macos ]
path: namer_app
flutter: build macos
- name: Build Linux app
platforms: [ linux ]
path: namer_app
flutter: build linux
- name: Build Windows app
platforms: [ windows ]
path: namer_app
flutter: build windows
- name: Copy step_03
copydir:
from: namer_app
to: step_03
- name: Flutter clean
path: step_03
flutter: clean
- name: step_04_a_widget
steps:
- name: Remove generated code
rmdir: step_04_a_widget
- name: Add button code
path: namer_app/lib/main.dart
patch-u: |
--- b/namer/step_04_a_widget/lib/main.dart
+++ a/namer/step_04_a_widget/lib/main.dart
@@ -37,8 +37,14 @@ class MyHomePage extends StatelessWidget {
return Scaffold(
body: Column(
children: [
- Text('A random idea:'),
+ Text('A random AWESOME idea:'),
Text(appState.current.asLowerCase),
+ ElevatedButton(
+ onPressed: () {
+ print('button pressed!');
+ },
+ child: Text('Next'),
+ ),
],
),
);
- name: Patch test/widget_test.dart
path: namer_app/test/widget_test.dart
patch-u: |
--- b/namer/step_04_a_widget/test/widget_test.dart
+++ a/namer/step_04_a_widget/test/widget_test.dart
@@ -5,6 +5,6 @@ import 'package:namer_app/main.dart';
void main() {
testWidgets('App starts', (WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
- expect(find.text('A random idea:'), findsOneWidget);
+ expect(find.text('A random AWESOME idea:'), findsOneWidget);
});
}
- name: Copy step_04_a_widget
copydir:
from: namer_app
to: step_04_a_widget
- name: step_04_b_behavior
steps:
- name: Remove generated code
rmdir: step_04_b_behavior
- name: Add button behavior
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -27,6 +27,11 @@ class MyApp extends StatelessWidget {
class MyAppState extends ChangeNotifier {
var current = WordPair.random();
+
+ void getNext() {
+ current = WordPair.random();
+ notifyListeners();
+ }
}
class MyHomePage extends StatelessWidget {
@@ -41,7 +46,7 @@ class MyHomePage extends StatelessWidget {
Text(appState.current.asLowerCase),
ElevatedButton(
onPressed: () {
- print('button pressed!');
+ appState.getNext();
},
child: Text('Next'),
),
- name: Add additional test
path: namer_app/test/widget_test.dart
patch-u: |
--- a/namer_app/test/widget_test.dart
+++ b/namer_app/test/widget_test.dart
@@ -1,3 +1,4 @@
+import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:namer_app/main.dart';
@@ -6,5 +7,45 @@
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.',
+ );
});
}
- name: Copy step_04_b_behavior
copydir:
from: namer_app
to: step_04_b_behavior
- name: step_05_a_pair
steps:
- name: Remove generated code
rmdir: step_05_a_pair
- name: Introduce pair variable
path: namer_app/lib/main.dart
patch-u: |
--- b/namer/step_05_a_pair/lib/main.dart
+++ a/namer/step_05_a_pair/lib/main.dart
@@ -38,12 +38,13 @@ class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
var appState = context.watch<MyAppState>();
+ var pair = appState.current;
return Scaffold(
body: Column(
children: [
Text('A random AWESOME idea:'),
- Text(appState.current.asLowerCase),
+ Text(pair.asLowerCase),
ElevatedButton(
onPressed: () {
appState.getNext();
- name: Copy step_05_a_pair
copydir:
from: namer_app
to: step_05_a_pair
- name: step_05_b_extract
steps:
- name: Remove generated code
rmdir: step_05_b_extract
- name: Extract BigCard
path: namer_app/lib/main.dart
patch-u: |
--- b/namer/step_05_b_extract/lib/main.dart
+++ a/namer/step_05_b_extract/lib/main.dart
@@ -44,7 +44,7 @@ class MyHomePage extends StatelessWidget {
body: Column(
children: [
Text('A random AWESOME idea:'),
- Text(pair.asLowerCase),
+ BigCard(pair: pair),
ElevatedButton(
onPressed: () {
appState.getNext();
@@ -56,3 +56,17 @@ class MyHomePage extends StatelessWidget {
);
}
}
+
+class BigCard extends StatelessWidget {
+ const BigCard({
+ super.key,
+ required this.pair,
+ });
+
+ final WordPair pair;
+
+ @override
+ Widget build(BuildContext context) {
+ return Text(pair.asLowerCase);
+ }
+}
- name: Update test to use BigCard
path: namer_app/test/widget_test.dart
patch-u: |
--- a/namer_app/test/widget_test.dart
+++ b/namer_app/test/widget_test.dart
@@ -13,13 +13,10 @@ void main() {
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;
+ final wordPairTextWidget = tester.widget<Text>(find.descendant(
+ of: find.byType(BigCard),
+ matching: find.byType(Text),
+ ));
return wordPairTextWidget.data!;
}
- name: Copy step_05_b_extract
copydir:
from: namer_app
to: step_05_b_extract
- name: step_05_c_card_padding
steps:
- name: Remove generated code
rmdir: step_05_c_card_padding
- name: Add Card and Padding
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -67,6 +67,11 @@ class BigCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
- return Text(pair.asLowerCase);
+ return Card(
+ child: Padding(
+ padding: const EdgeInsets.all(20),
+ child: Text(pair.asLowerCase),
+ ),
+ );
}
}
- name: Copy step_05_c_card_padding
copydir:
from: namer_app
to: step_05_c_card_padding
- name: step_05_d_theme
steps:
- name: Remove generated code
rmdir: step_05_d_theme
- name: Add Theme
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -67,7 +67,10 @@ class BigCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+
return Card(
+ color: theme.colorScheme.primary,
child: Padding(
padding: const EdgeInsets.all(20),
child: Text(pair.asLowerCase),
- name: Copy step_05_d_theme
copydir:
from: namer_app
to: step_05_d_theme
- name: step_05_e_text_style
steps:
- name: Remove generated code
rmdir: step_05_e_text_style
- name: Add textStyle
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -68,12 +68,15 @@ class BigCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
+ final style = theme.textTheme.displayMedium!.copyWith(
+ color: theme.colorScheme.onPrimary,
+ );
return Card(
color: theme.colorScheme.primary,
child: Padding(
padding: const EdgeInsets.all(20),
- child: Text(pair.asLowerCase),
+ child: Text(pair.asLowerCase, style: style),
),
);
}
- name: Copy step_05_e_text_style
copydir:
from: namer_app
to: step_05_e_text_style
- name: step_05_f_accessibility
steps:
- name: Remove generated code
rmdir: step_05_f_accessibility
- name: Add semanticsLabel
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -76,7 +76,11 @@ class BigCard extends StatelessWidget {
color: theme.colorScheme.primary,
child: Padding(
padding: const EdgeInsets.all(20),
- child: Text(pair.asLowerCase, style: style),
+ child: Text(
+ pair.asLowerCase,
+ style: style,
+ semanticsLabel: "${pair.first} ${pair.second}",
+ ),
),
);
}
- name: Copy step_05_f_accessibility
copydir:
from: namer_app
to: step_05_f_accessibility
- name: step_05_g_center_vertical
steps:
- name: Remove generated code
rmdir: step_05_g_center_vertical
- name: Center column vertically
path: namer_app/lib/main.dart
patch-u: |
--- b/namer/step_05_g_center_vertical/lib/main.dart
+++ a/namer/step_05_g_center_vertical/lib/main.dart
@@ -42,6 +42,7 @@ class MyHomePage extends StatelessWidget {
return Scaffold(
body: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('A random AWESOME idea:'),
BigCard(pair: pair),
- name: Copy step_05_g_center_vertical
copydir:
from: namer_app
to: step_05_g_center_vertical
- name: step_05_h_center_horizontal
steps:
- name: Remove generated code
rmdir: step_05_h_center_horizontal
- name: Center column horizontally
path: namer_app/lib/main.dart
patch-u: |
--- b/namer/step_05_h_center_horizontal/lib/main.dart
+++ a/namer/step_05_h_center_horizontal/lib/main.dart
@@ -41,18 +41,20 @@ class MyHomePage extends StatelessWidget {
var pair = appState.current;
return Scaffold(
- body: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Text('A random AWESOME idea:'),
- BigCard(pair: pair),
- ElevatedButton(
- onPressed: () {
- appState.getNext();
- },
- child: Text('Next'),
- ),
- ],
+ body: Center(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Text('A random AWESOME idea:'),
+ BigCard(pair: pair),
+ ElevatedButton(
+ onPressed: () {
+ appState.getNext();
+ },
+ child: Text('Next'),
+ ),
+ ],
+ ),
),
);
}
- name: Copy step_05_h_center_horizontal
copydir:
from: namer_app
to: step_05_h_center_horizontal
- name: step_05_i_optional_changes
steps:
- name: Remove generated code
rmdir: step_05_i_optional_changes
- name: Remove text, add SizedBox
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -45,8 +45,8 @@ class MyHomePage extends StatelessWidget {
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
- Text('A random AWESOME idea:'),
BigCard(pair: pair),
+ SizedBox(height: 10),
ElevatedButton(
onPressed: () {
appState.getNext();
- name: Update test
path: namer_app/test/widget_test.dart
patch-u: |
--- a/namer_app/test/widget_test.dart
+++ b/namer_app/test/widget_test.dart
@@ -6,7 +6,7 @@ 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);
+ expect(find.text('Next'), findsOneWidget);
});
testWidgets('Tapping button changes word pair', (WidgetTester tester) async {
- name: Copy step_05_i_optional_changes
copydir:
from: namer_app
to: step_05_i_optional_changes
- name: step_06_a_business_logic
steps:
- name: Remove generated code
rmdir: step_06_a_business_logic
- name: Add 'Like' button business logic
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -32,6 +32,17 @@ class MyAppState extends ChangeNotifier {
current = WordPair.random();
notifyListeners();
}
+
+ var favorites = <WordPair>[];
+
+ void toggleFavorite() {
+ if (favorites.contains(current)) {
+ favorites.remove(current);
+ } else {
+ favorites.add(current);
+ }
+ notifyListeners();
+ }
}
class MyHomePage extends StatelessWidget {
- name: Copy step_06_a_business_logic
copydir:
from: namer_app
to: step_06_a_business_logic
- name: step_06_b_add_row
steps:
- name: Remove generated code
rmdir: step_06_b_add_row
- name: Add row for buttons
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -58,11 +58,16 @@ class MyHomePage extends StatelessWidget {
children: [
BigCard(pair: pair),
SizedBox(height: 10),
- ElevatedButton(
- onPressed: () {
- appState.getNext();
- },
- child: Text('Next'),
+ Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ ElevatedButton(
+ onPressed: () {
+ appState.getNext();
+ },
+ child: Text('Next'),
+ ),
+ ],
),
],
),
- name: Copy step_06_b_add_row
copydir:
from: namer_app
to: step_06_b_add_row
- name: step_06_c_add_like_button
steps:
- name: Remove generated code
rmdir: step_06_c_add_like_button
- name: Add 'Like' button to UI
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -51,6 +51,13 @@ class MyHomePage extends StatelessWidget {
var appState = context.watch<MyAppState>();
var pair = appState.current;
+ IconData icon;
+ if (appState.favorites.contains(pair)) {
+ icon = Icons.favorite;
+ } else {
+ icon = Icons.favorite_border;
+ }
+
return Scaffold(
body: Center(
child: Column(
@@ -61,6 +68,14 @@ class MyHomePage extends StatelessWidget {
Row(
mainAxisSize: MainAxisSize.min,
children: [
+ ElevatedButton.icon(
+ onPressed: () {
+ appState.toggleFavorite();
+ },
+ icon: Icon(icon),
+ label: Text('Like'),
+ ),
+ SizedBox(width: 10),
ElevatedButton(
onPressed: () {
appState.getNext();
- name: Add test to check 'Like' button
path: namer_app/test/widget_test.dart
patch-u: |
--- a/namer_app/test/widget_test.dart
+++ b/namer_app/test/widget_test.dart
@@ -45,4 +45,26 @@
'randomly generated at all. The button does not work.',
);
});
+
+ testWidgets('Tapping "Like" changes icon', (WidgetTester tester) async {
+ await tester.pumpWidget(const MyApp());
+
+ Finder findElevatedButtonByIcon(IconData icon) {
+ return find.descendant(
+ of: find.bySubtype<ElevatedButton>(),
+ matching: find.byIcon(icon),
+ );
+ }
+
+ // At start: an outlined heart icon.
+ expect(findElevatedButtonByIcon(Icons.favorite_border), findsOneWidget);
+ expect(findElevatedButtonByIcon(Icons.favorite), findsNothing);
+
+ await tester.tap(find.text('Like'));
+ await tester.pumpAndSettle();
+
+ // After tap: a full heart icon.
+ expect(findElevatedButtonByIcon(Icons.favorite_border), findsNothing);
+ expect(findElevatedButtonByIcon(Icons.favorite), findsOneWidget);
+ });
}
- name: Copy step_06_c_add_like_button
copydir:
from: namer_app
to: step_06_c_add_like_button
- name: step_07_a_split_my_home_page
steps:
- name: Remove generated code
rmdir: step_07_a_split_my_home_page
- name: Split MyHomePage into two widgets
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -48,6 +48,43 @@
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
+ return Scaffold(
+ body: Row(
+ children: [
+ SafeArea(
+ child: NavigationRail(
+ extended: false,
+ destinations: [
+ NavigationRailDestination(
+ icon: Icon(Icons.home),
+ label: Text('Home'),
+ ),
+ NavigationRailDestination(
+ icon: Icon(Icons.favorite),
+ label: Text('Favorites'),
+ ),
+ ],
+ selectedIndex: 0,
+ onDestinationSelected: (value) {
+ print('selected: $value');
+ },
+ ),
+ ),
+ Expanded(
+ child: Container(
+ color: Theme.of(context).colorScheme.primaryContainer,
+ child: GeneratorPage(),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class GeneratorPage extends StatelessWidget {
+ @override
+ Widget build(BuildContext context) {
var appState = context.watch<MyAppState>();
var pair = appState.current;
@@ -58,34 +95,32 @@
icon = Icons.favorite_border;
}
- return Scaffold(
- body: Center(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- BigCard(pair: pair),
- SizedBox(height: 10),
- Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- ElevatedButton.icon(
- onPressed: () {
- appState.toggleFavorite();
- },
- icon: Icon(icon),
- label: Text('Like'),
- ),
- SizedBox(width: 10),
- ElevatedButton(
- onPressed: () {
- appState.getNext();
- },
- child: Text('Next'),
- ),
- ],
- ),
- ],
- ),
+ return Center(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ BigCard(pair: pair),
+ SizedBox(height: 10),
+ Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ ElevatedButton.icon(
+ onPressed: () {
+ appState.toggleFavorite();
+ },
+ icon: Icon(icon),
+ label: Text('Like'),
+ ),
+ SizedBox(width: 10),
+ ElevatedButton(
+ onPressed: () {
+ appState.getNext();
+ },
+ child: Text('Next'),
+ ),
+ ],
+ ),
+ ],
),
);
}
- name: Copy step_07_a_split_my_home_page
copydir:
from: namer_app
to: step_07_a_split_my_home_page
- name: step_07_b_convert_to_stateful
steps:
- name: Remove generated code
rmdir: step_07_b_convert_to_stateful
- name: Convert MyHomePage to StatefulWidget
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -45,7 +45,12 @@ class MyAppState extends ChangeNotifier {
}
}
-class MyHomePage extends StatelessWidget {
+class MyHomePage extends StatefulWidget {
+ @override
+ State<MyHomePage> createState() => _MyHomePageState();
+}
+
+class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
- name: Copy step_07_b_convert_to_stateful
copydir:
from: namer_app
to: step_07_b_convert_to_stateful
- name: step_07_c_add_selectedindex
steps:
- name: Remove generated code
rmdir: step_07_c_add_selectedindex
- name: Add selectedIndex
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -51,6 +51,8 @@
}
class _MyHomePageState extends State<MyHomePage> {
+ var selectedIndex = 0;
+
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -69,9 +71,11 @@
label: Text('Favorites'),
),
],
- selectedIndex: 0,
+ selectedIndex: selectedIndex,
onDestinationSelected: (value) {
- print('selected: $value');
+ setState(() {
+ selectedIndex = value;
+ });
},
),
),
- name: Copy step_07_c_add_selectedindex
copydir:
from: namer_app
to: step_07_c_add_selectedindex
- name: step_07_d_use_selectedindex
steps:
- name: Remove generated code
rmdir: step_07_d_use_selectedindex
- name: Use selectedIndex
path: namer_app/lib/main.dart
patch-u: |
--- b/namer/step_07_d_use_selectedindex/lib/main.dart
+++ a/namer/step_07_d_use_selectedindex/lib/main.dart
@@ -55,6 +55,16 @@ class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
+ Widget page;
+ switch (selectedIndex) {
+ case 0:
+ page = GeneratorPage();
+ case 1:
+ page = Placeholder();
+ default:
+ throw UnimplementedError('no widget for $selectedIndex');
+ }
+
return Scaffold(
body: Row(
children: [
@@ -82,7 +92,7 @@ class _MyHomePageState extends State<MyHomePage> {
Expanded(
child: Container(
color: Theme.of(context).colorScheme.primaryContainer,
- child: GeneratorPage(),
+ child: page,
),
),
],
- name: Copy step_07_d_use_selectedindex
copydir:
from: namer_app
to: step_07_d_use_selectedindex
- name: step_07_e_add_layout_builder
steps:
- name: Remove generated code
rmdir: step_07_e_add_layout_builder
- name: Add LayoutBuilder
path: namer_app/lib/main.dart
patch-u: |
--- a/namer_app/lib/main.dart
+++ b/namer_app/lib/main.dart
@@ -65,39 +65,41 @@
throw UnimplementedError('no widget for $selectedIndex');
}
- return Scaffold(
- body: Row(
- children: [
- SafeArea(
- child: NavigationRail(
- extended: false,
- destinations: [
- NavigationRailDestination(
- icon: Icon(Icons.home),
- label: Text('Home'),
- ),
- NavigationRailDestination(
- icon: Icon(Icons.favorite),
- label: Text('Favorites'),
- ),
- ],
- selectedIndex: selectedIndex,
- onDestinationSelected: (value) {
- setState(() {
- selectedIndex = value;
- });
- },
+ return LayoutBuilder(builder: (context, constraints) {
+ return Scaffold(
+ body: Row(
+ children: [
+ SafeArea(
+ child: NavigationRail(
+ extended: constraints.maxWidth >= 600,
+ destinations: [
+ NavigationRailDestination(
+ icon: Icon(Icons.home),
+ label: Text('Home'),
+ ),
+ NavigationRailDestination(
+ icon: Icon(Icons.favorite),
+ label: Text('Favorites'),
+ ),
+ ],
+ selectedIndex: selectedIndex,
+ onDestinationSelected: (value) {
+ setState(() {
+ selectedIndex = value;
+ });
+ },
+ ),
),
- ),
- Expanded(
- child: Container(
- color: Theme.of(context).colorScheme.primaryContainer,
- child: page,
+ Expanded(
+ child: Container(
+ color: Theme.of(context).colorScheme.primaryContainer,
+ child: page,
+ ),
),
- ),
- ],
- ),
- );
+ ],
+ ),
+ );
+ });
}
}
- name: Copy step_07_e_add_layout_builder
copydir:
from: namer_app
to: step_07_e_add_layout_builder
- name: step_08
steps:
- name: Remove generated code
rmdir: step_08
- name: Add FavoritesPage
path: namer_app/lib/main.dart
patch-u: |
--- b/namer/step_08/lib/main.dart
+++ a/namer/step_08/lib/main.dart
@@ -60,7 +60,7 @@ class _MyHomePageState extends State<MyHomePage> {
case 0:
page = GeneratorPage();
case 1:
- page = Placeholder();
+ page = FavoritesPage();
default:
throw UnimplementedError('no widget for $selectedIndex');
}
@@ -175,3 +175,31 @@ class BigCard extends StatelessWidget {
);
}
}
+
+class FavoritesPage extends StatelessWidget {
+ @override
+ Widget build(BuildContext context) {
+ var appState = context.watch<MyAppState>();
+
+ if (appState.favorites.isEmpty) {
+ return Center(
+ child: Text('No favorites yet.'),
+ );
+ }
+
+ return ListView(
+ children: [
+ Padding(
+ padding: const EdgeInsets.all(20),
+ child: Text('You have '
+ '${appState.favorites.length} favorites:'),
+ ),
+ for (var pair in appState.favorites)
+ ListTile(
+ leading: Icon(Icons.favorite),
+ title: Text(pair.asLowerCase),
+ ),
+ ],
+ );
+ }
+}
- name: Add test to check FavoritesPage
path: namer_app/test/widget_test.dart
patch-u: |
--- a/namer_app/test/widget_test.dart
+++ b/namer_app/test/widget_test.dart
@@ -67,4 +67,45 @@ void main() {
expect(findElevatedButtonByIcon(Icons.favorite_border), findsNothing);
expect(findElevatedButtonByIcon(Icons.favorite), findsOneWidget);
});
+
+ testWidgets('Liked word pair shows up in Favorites',
+ (WidgetTester tester) async {
+ await tester.pumpWidget(const MyApp());
+
+ // Find the currently shown word pair.
+ final wordPairTextWidget = tester.widget<Text>(find.descendant(
+ of: find.byType(BigCard),
+ matching: find.byType(Text),
+ ));
+ final current = wordPairTextWidget.data!;
+
+ // Go to the Favorites page.
+ await tester.tap(find.descendant(
+ of: find.byType(NavigationRail),
+ matching: find.byIcon(Icons.favorite),
+ ));
+ await tester.pumpAndSettle();
+
+ // Not there yet.
+ expect(find.text(current), findsNothing);
+
+ // Go back to the Generator page.
+ await tester.tap(find.descendant(
+ of: find.byType(NavigationRail),
+ matching: find.byIcon(Icons.home),
+ ));
+ await tester.pumpAndSettle();
+
+ await tester.tap(find.text('Like'));
+
+ // Go to Favorites page once again.
+ await tester.tap(find.descendant(
+ of: find.byType(NavigationRail),
+ matching: find.byIcon(Icons.favorite),
+ ));
+ await tester.pumpAndSettle();
+
+ // Should be there.
+ expect(find.text(current), findsOneWidget);
+ });
}
- name: Add accessibility guidelines test
path: namer_app/test/a11y_test.dart
replace-contents: |
import 'package:flutter_test/flutter_test.dart';
import 'package:namer_app/main.dart';
void main() {
testWidgets('Follows a11y guidelines', (WidgetTester tester) async {
// #docregion insideTest
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(MyApp());
// Checks that tappable nodes have a minimum size of 48 by 48 pixels
// for Android.
await expectLater(tester, meetsGuideline(androidTapTargetGuideline));
// Checks that tappable nodes have a minimum size of 44 by 44 pixels
// for iOS.
await expectLater(tester, meetsGuideline(iOSTapTargetGuideline));
// Checks that touch targets with a tap or long press action are labeled.
await expectLater(tester, meetsGuideline(labeledTapTargetGuideline));
// Checks whether semantic nodes meet the minimum text contrast levels.
// The recommended text contrast is 3:1 for larger text
// (18 point and above regular).
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
// #enddocregion insideTest
});
}
- name: Build iOS simulator bundle
platforms: [ macos ]
path: namer_app
flutter: build ios --simulator
- name: Build macOS app
platforms: [ macos ]
path: namer_app
flutter: build macos
- name: Build Linux app
platforms: [ linux ]
path: namer_app
flutter: build linux
- name: Build Windows app
platforms: [ windows ]
path: namer_app
flutter: build windows
- name: Add cupertino_icons for web build
path: namer_app
flutter: pub add cupertino_icons
- name: Build Web app
path: namer_app
flutter: build web
- name: Copy step_08
copydir:
from: namer_app
to: step_08
- name: Flutter clean
path: step_08
flutter: clean
- name: Cleanup
rmdir: namer_app
| codelabs/namer/codelab_rebuild.yaml/0 | {
"file_path": "codelabs/namer/codelab_rebuild.yaml",
"repo_id": "codelabs",
"token_count": 24713
} | 65 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/namer/step_04_a_widget/android/gradle.properties/0 | {
"file_path": "codelabs/namer/step_04_a_widget/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 66 |
#include "Generated.xcconfig"
| codelabs/namer/step_05_a_pair/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_a_pair/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 67 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/namer/step_05_a_pair/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_a_pair/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 68 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/namer/step_05_b_extract/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_b_extract/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 69 |
#include "Generated.xcconfig"
| codelabs/namer/step_05_f_accessibility/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_f_accessibility/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 70 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/namer/step_05_f_accessibility/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_f_accessibility/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 71 |
#import "GeneratedPluginRegistrant.h"
| codelabs/namer/step_05_g_center_vertical/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/namer/step_05_g_center_vertical/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 72 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/namer/step_05_g_center_vertical/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/namer/step_05_g_center_vertical/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 73 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/namer/step_07_c_add_selectedindex/android/gradle.properties/0 | {
"file_path": "codelabs/namer/step_07_c_add_selectedindex/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 74 |
#include "Generated.xcconfig"
| codelabs/namer/step_07_e_add_layout_builder/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_07_e_add_layout_builder/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 75 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/namer/step_07_e_add_layout_builder/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_07_e_add_layout_builder/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 76 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/namer/step_08/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/namer/step_08/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 77 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/next-gen-ui/step_02_b/android/gradle.properties/0 | {
"file_path": "codelabs/next-gen-ui/step_02_b/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 78 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/next-gen-ui/step_03_c/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/next-gen-ui/step_03_c/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 79 |
#import "GeneratedPluginRegistrant.h"
| codelabs/next-gen-ui/step_04_a/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/next-gen-ui/step_04_a/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 80 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/next-gen-ui/step_04_c/android/gradle.properties/0 | {
"file_path": "codelabs/next-gen-ui/step_04_c/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 81 |
// 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:math';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animate/flutter_animate.dart';
import '../assets.dart';
import '../orb_shader/orb_shader_config.dart';
import '../orb_shader/orb_shader_widget.dart';
import '../styles.dart';
import 'particle_overlay.dart';
import 'title_screen_ui.dart';
class TitleScreen extends StatefulWidget {
const TitleScreen({super.key});
@override
State<TitleScreen> createState() => _TitleScreenState();
}
class _TitleScreenState extends State<TitleScreen>
with SingleTickerProviderStateMixin {
final _orbKey = GlobalKey<OrbShaderWidgetState>();
/// Editable Settings
/// 0-1, receive lighting strength
final _minReceiveLightAmt = .35;
final _maxReceiveLightAmt = .7;
/// 0-1, emit lighting strength
final _minEmitLightAmt = .5;
final _maxEmitLightAmt = 1;
/// Internal
var _mousePos = Offset.zero;
Color get _emitColor =>
AppColors.emitColors[_difficultyOverride ?? _difficulty];
Color get _orbColor =>
AppColors.orbColors[_difficultyOverride ?? _difficulty];
/// Currently selected difficulty
int _difficulty = 0;
/// Currently focused difficulty (if any)
int? _difficultyOverride;
double _orbEnergy = 0;
double _minOrbEnergy = 0;
double get _finalReceiveLightAmt {
final light =
lerpDouble(_minReceiveLightAmt, _maxReceiveLightAmt, _orbEnergy) ?? 0;
return light + _pulseEffect.value * .05 * _orbEnergy;
}
double get _finalEmitLightAmt {
return lerpDouble(_minEmitLightAmt, _maxEmitLightAmt, _orbEnergy) ?? 0;
}
late final _pulseEffect = AnimationController(
vsync: this,
duration: _getRndPulseDuration(),
lowerBound: -1,
upperBound: 1,
);
Duration _getRndPulseDuration() => 100.ms + 200.ms * Random().nextDouble();
double _getMinEnergyForDifficulty(int difficulty) => switch (difficulty) {
1 => 0.3,
2 => 0.6,
_ => 0,
};
@override
void initState() {
super.initState();
_pulseEffect.forward();
_pulseEffect.addListener(_handlePulseEffectUpdate);
}
void _handlePulseEffectUpdate() {
if (_pulseEffect.status == AnimationStatus.completed) {
_pulseEffect.reverse();
_pulseEffect.duration = _getRndPulseDuration();
} else if (_pulseEffect.status == AnimationStatus.dismissed) {
_pulseEffect.duration = _getRndPulseDuration();
_pulseEffect.forward();
}
}
void _handleDifficultyPressed(int value) {
setState(() => _difficulty = value);
_bumpMinEnergy();
}
Future<void> _bumpMinEnergy([double amount = 0.1]) async {
setState(() {
_minOrbEnergy = _getMinEnergyForDifficulty(_difficulty) + amount;
});
await Future<void>.delayed(.2.seconds);
setState(() {
_minOrbEnergy = _getMinEnergyForDifficulty(_difficulty);
});
}
void _handleStartPressed() => _bumpMinEnergy(0.3);
void _handleDifficultyFocused(int? value) {
setState(() {
_difficultyOverride = value;
if (value == null) {
_minOrbEnergy = _getMinEnergyForDifficulty(_difficulty);
} else {
_minOrbEnergy = _getMinEnergyForDifficulty(value);
}
});
}
/// Update mouse position so the orbWidget can use it, doing it here prevents
/// btns from blocking the mouse-move events in the widget itself.
void _handleMouseMove(PointerHoverEvent e) {
setState(() {
_mousePos = e.localPosition;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: Center(
child: MouseRegion(
onHover: _handleMouseMove,
child: _AnimatedColors(
orbColor: _orbColor,
emitColor: _emitColor,
builder: (_, orbColor, emitColor) {
return Stack(
children: [
/// Bg-Base
Image.asset(AssetPaths.titleBgBase),
/// Bg-Receive
_LitImage(
color: orbColor,
imgSrc: AssetPaths.titleBgReceive,
pulseEffect: _pulseEffect,
lightAmt: _finalReceiveLightAmt,
),
/// Orb
Positioned.fill(
child: Stack(
children: [
// Orb
OrbShaderWidget(
key: _orbKey,
mousePos: _mousePos,
minEnergy: _minOrbEnergy,
config: OrbShaderConfig(
ambientLightColor: orbColor,
materialColor: orbColor,
lightColor: orbColor,
),
onUpdate: (energy) => setState(() {
_orbEnergy = energy;
}),
),
],
),
),
/// Mg-Base
_LitImage(
imgSrc: AssetPaths.titleMgBase,
color: orbColor,
pulseEffect: _pulseEffect,
lightAmt: _finalReceiveLightAmt,
),
/// Mg-Receive
_LitImage(
imgSrc: AssetPaths.titleMgReceive,
color: orbColor,
pulseEffect: _pulseEffect,
lightAmt: _finalReceiveLightAmt,
),
/// Mg-Emit
_LitImage(
imgSrc: AssetPaths.titleMgEmit,
color: emitColor,
pulseEffect: _pulseEffect,
lightAmt: _finalEmitLightAmt,
),
/// Particle Field
Positioned.fill(
child: IgnorePointer(
child: ParticleOverlay(
color: orbColor,
energy: _orbEnergy,
),
),
),
/// Fg-Rocks
Image.asset(AssetPaths.titleFgBase),
/// Fg-Receive
_LitImage(
imgSrc: AssetPaths.titleFgReceive,
color: orbColor,
pulseEffect: _pulseEffect,
lightAmt: _finalReceiveLightAmt,
),
/// Fg-Emit
_LitImage(
imgSrc: AssetPaths.titleFgEmit,
color: emitColor,
pulseEffect: _pulseEffect,
lightAmt: _finalEmitLightAmt,
),
/// UI
Positioned.fill(
child: TitleScreenUi(
difficulty: _difficulty,
onDifficultyFocused: _handleDifficultyFocused,
onDifficultyPressed: _handleDifficultyPressed,
onStartPressed: _handleStartPressed,
),
),
],
).animate().fadeIn(duration: 1.seconds, delay: .3.seconds);
},
),
),
),
);
}
}
class _LitImage extends StatelessWidget {
const _LitImage({
required this.color,
required this.imgSrc,
required this.pulseEffect,
required this.lightAmt,
});
final Color color;
final String imgSrc;
final AnimationController pulseEffect;
final double lightAmt;
@override
Widget build(BuildContext context) {
final hsl = HSLColor.fromColor(color);
return ListenableBuilder(
listenable: pulseEffect,
builder: (context, child) {
return Image.asset(
imgSrc,
color: hsl.withLightness(hsl.lightness * lightAmt).toColor(),
colorBlendMode: BlendMode.modulate,
);
},
);
}
}
class _AnimatedColors extends StatelessWidget {
const _AnimatedColors({
required this.emitColor,
required this.orbColor,
required this.builder,
});
final Color emitColor;
final Color orbColor;
final Widget Function(BuildContext context, Color orbColor, Color emitColor)
builder;
@override
Widget build(BuildContext context) {
final duration = .5.seconds;
return TweenAnimationBuilder(
tween: ColorTween(begin: emitColor, end: emitColor),
duration: duration,
builder: (_, emitColor, __) {
return TweenAnimationBuilder(
tween: ColorTween(begin: orbColor, end: orbColor),
duration: duration,
builder: (context, orbColor, __) {
return builder(context, orbColor!, emitColor!);
},
);
},
);
}
}
| codelabs/next-gen-ui/step_06/lib/title_screen/title_screen.dart/0 | {
"file_path": "codelabs/next-gen-ui/step_06/lib/title_screen/title_screen.dart",
"repo_id": "codelabs",
"token_count": 4496
} | 82 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/next-gen-ui/step_06/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/next-gen-ui/step_06/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 83 |
#import "GeneratedPluginRegistrant.h"
| codelabs/testing_codelab/step_03/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/testing_codelab/step_03/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 84 |
# Board game app built with TensorFlow Agents and Flutter
This folder contains the code for [TensorFlow Agents](https://www.tensorflow.org/agents) + Flutter codelab. It is broken down into 6 steps:
1. Create a TensorFlow Agents Python environment
2. Train the game agent with TensorFlow Agents
3. Deploy the trained model with TensorFlow Serving
4. Create the Flutter app for Android and iOS
5. Run the Flutter app on the desktop platforms
6. Run the Flutter app on the web platform
 | codelabs/tfagents-flutter/README.md/0 | {
"file_path": "codelabs/tfagents-flutter/README.md",
"repo_id": "codelabs",
"token_count": 141
} | 85 |
#include "Generated.xcconfig"
| codelabs/tfagents-flutter/finished/frontend/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/finished/frontend/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 86 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/tfagents-flutter/finished/frontend/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/finished/frontend/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 87 |
#include "Generated.xcconfig"
| codelabs/tfagents-flutter/step0/frontend/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/step0/frontend/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 88 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/tfagents-flutter/step0/frontend/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/step0/frontend/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 89 |
#include "Generated.xcconfig"
| codelabs/tfagents-flutter/step1/frontend/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/step1/frontend/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 90 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/tfagents-flutter/step1/frontend/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/tfagents-flutter/step1/frontend/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 91 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/tfrs-flutter/step1/frontend/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "codelabs/tfrs-flutter/step1/frontend/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 92 |
#include "Generated.xcconfig"
| codelabs/tfrs-flutter/step3/frontend/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/tfrs-flutter/step3/frontend/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 93 |
from flask import Flask
from flask_cors import CORS
from flask import jsonify, make_response, request
import json, requests
import numpy as np
RETRIEVAL_URL = "http://localhost:8501/v1/models/retrieval:predict"
RANKING_URL = "http://localhost:8501/v1/models/ranking:predict"
NUM_OF_CANDIDATES = 10
app = Flask(__name__)
CORS(app)
@app.route("/recommend", methods=["POST"])
def get_recommendations():
user_id = request.get_json()["user_id"]
retrieval_request = json.dumps({"instances": [user_id]})
retrieval_response = requests.post(RETRIEVAL_URL, data=retrieval_request)
movie_candidates = retrieval_response.json()["predictions"][0]["output_2"]
ranking_queries = [
{"user_id": u, "movie_title": m}
for (u, m) in zip([user_id] * NUM_OF_CANDIDATES, movie_candidates)
]
ranking_request = json.dumps({"instances": ranking_queries})
ranking_response = requests.post(RANKING_URL, data=ranking_request)
movies_scores = list(np.squeeze(ranking_response.json()["predictions"]))
ranked_movies = [
m[1] for m in sorted(list(zip(movies_scores, movie_candidates)), reverse=True)
]
return make_response(jsonify({"movies": ranked_movies}), 200)
if __name__ == "__main__":
app.run(debug=True)
| codelabs/tfrs-flutter/step5/backend/recommender.py/0 | {
"file_path": "codelabs/tfrs-flutter/step5/backend/recommender.py",
"repo_id": "codelabs",
"token_count": 485
} | 94 |
#import "GeneratedPluginRegistrant.h"
| codelabs/tfrs-flutter/step5/frontend/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/tfrs-flutter/step5/frontend/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 95 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/tfrs-flutter/step5/frontend/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/tfrs-flutter/step5/frontend/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 96 |
package com.example.tfserving_flutter
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| codelabs/tfserving-flutter/codelab2/starter/android/app/src/main/kotlin/com/example/tfserving_flutter/MainActivity.kt/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/android/app/src/main/kotlin/com/example/tfserving_flutter/MainActivity.kt",
"repo_id": "codelabs",
"token_count": 40
} | 97 |
///
// Generated code. Do not modify.
// source: tensorflow/core/example/example.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:protobuf/protobuf.dart' as $pb;
import 'feature.pb.dart' as $0;
class Example extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'Example',
package: const $pb.PackageName(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'tensorflow'),
createEmptyInstance: create)
..aOM<$0.Features>(
1,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'features',
subBuilder: $0.Features.create)
..hasRequiredFields = false;
Example._() : super();
factory Example({
$0.Features? features,
}) {
final _result = create();
if (features != null) {
_result.features = features;
}
return _result;
}
factory Example.fromBuffer($core.List<$core.int> i,
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromBuffer(i, r);
factory Example.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')
Example clone() => Example()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
Example copyWith(void Function(Example) updates) =>
super.copyWith((message) => updates(message as Example))
as Example; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static Example create() => Example._();
Example createEmptyInstance() => create();
static $pb.PbList<Example> createRepeated() => $pb.PbList<Example>();
@$core.pragma('dart2js:noInline')
static Example getDefault() =>
_defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<Example>(create);
static Example? _defaultInstance;
@$pb.TagNumber(1)
$0.Features get features => $_getN(0);
@$pb.TagNumber(1)
set features($0.Features v) {
setField(1, v);
}
@$pb.TagNumber(1)
$core.bool hasFeatures() => $_has(0);
@$pb.TagNumber(1)
void clearFeatures() => clearField(1);
@$pb.TagNumber(1)
$0.Features ensureFeatures() => $_ensure(0);
}
class SequenceExample extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'SequenceExample',
package: const $pb.PackageName(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'tensorflow'),
createEmptyInstance: create)
..aOM<$0.Features>(
1,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'context',
subBuilder: $0.Features.create)
..aOM<$0.FeatureLists>(
2,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'featureLists',
subBuilder: $0.FeatureLists.create)
..hasRequiredFields = false;
SequenceExample._() : super();
factory SequenceExample({
$0.Features? context,
$0.FeatureLists? featureLists,
}) {
final _result = create();
if (context != null) {
_result.context = context;
}
if (featureLists != null) {
_result.featureLists = featureLists;
}
return _result;
}
factory SequenceExample.fromBuffer($core.List<$core.int> i,
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromBuffer(i, r);
factory SequenceExample.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')
SequenceExample clone() => SequenceExample()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
SequenceExample copyWith(void Function(SequenceExample) updates) =>
super.copyWith((message) => updates(message as SequenceExample))
as SequenceExample; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static SequenceExample create() => SequenceExample._();
SequenceExample createEmptyInstance() => create();
static $pb.PbList<SequenceExample> createRepeated() =>
$pb.PbList<SequenceExample>();
@$core.pragma('dart2js:noInline')
static SequenceExample getDefault() => _defaultInstance ??=
$pb.GeneratedMessage.$_defaultFor<SequenceExample>(create);
static SequenceExample? _defaultInstance;
@$pb.TagNumber(1)
$0.Features get context => $_getN(0);
@$pb.TagNumber(1)
set context($0.Features v) {
setField(1, v);
}
@$pb.TagNumber(1)
$core.bool hasContext() => $_has(0);
@$pb.TagNumber(1)
void clearContext() => clearField(1);
@$pb.TagNumber(1)
$0.Features ensureContext() => $_ensure(0);
@$pb.TagNumber(2)
$0.FeatureLists get featureLists => $_getN(1);
@$pb.TagNumber(2)
set featureLists($0.FeatureLists v) {
setField(2, v);
}
@$pb.TagNumber(2)
$core.bool hasFeatureLists() => $_has(1);
@$pb.TagNumber(2)
void clearFeatureLists() => clearField(2);
@$pb.TagNumber(2)
$0.FeatureLists ensureFeatureLists() => $_ensure(1);
}
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/example/example.pb.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/example/example.pb.dart",
"repo_id": "codelabs",
"token_count": 2434
} | 98 |
///
// Generated code. Do not modify.
// source: tensorflow/core/framework/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
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/graph.pbenum.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/graph.pbenum.dart",
"repo_id": "codelabs",
"token_count": 115
} | 99 |
///
// 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,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 tensorShapeProtoDescriptor instead')
const TensorShapeProto$json = const {
'1': 'TensorShapeProto',
'2': const [
const {
'1': 'dim',
'3': 2,
'4': 3,
'5': 11,
'6': '.tensorflow.TensorShapeProto.Dim',
'10': 'dim'
},
const {'1': 'unknown_rank', '3': 3, '4': 1, '5': 8, '10': 'unknownRank'},
],
'3': const [TensorShapeProto_Dim$json],
};
@$core.Deprecated('Use tensorShapeProtoDescriptor instead')
const TensorShapeProto_Dim$json = const {
'1': 'Dim',
'2': const [
const {'1': 'size', '3': 1, '4': 1, '5': 3, '10': 'size'},
const {'1': 'name', '3': 2, '4': 1, '5': 9, '10': 'name'},
],
};
/// Descriptor for `TensorShapeProto`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List tensorShapeProtoDescriptor = $convert.base64Decode(
'ChBUZW5zb3JTaGFwZVByb3RvEjIKA2RpbRgCIAMoCzIgLnRlbnNvcmZsb3cuVGVuc29yU2hhcGVQcm90by5EaW1SA2RpbRIhCgx1bmtub3duX3JhbmsYAyABKAhSC3Vua25vd25SYW5rGi0KA0RpbRISCgRzaXplGAEgASgDUgRzaXplEhIKBG5hbWUYAiABKAlSBG5hbWU=');
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/tensor_shape.pbjson.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/framework/tensor_shape.pbjson.dart",
"repo_id": "codelabs",
"token_count": 713
} | 100 |
///
// Generated code. Do not modify.
// source: tensorflow/core/protobuf/saver.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:protobuf/protobuf.dart' as $pb;
import 'saver.pbenum.dart';
export 'saver.pbenum.dart';
class SaverDef extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'SaverDef',
package: const $pb.PackageName(
const $core.bool.fromEnvironment('protobuf.omit_message_names')
? ''
: 'tensorflow'),
createEmptyInstance: create)
..aOS(
1,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'filenameTensorName')
..aOS(
2,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'saveTensorName')
..aOS(
3,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'restoreOpName')
..a<$core.int>(
4,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'maxToKeep',
$pb.PbFieldType.O3)
..aOB(
5,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'sharded')
..a<$core.double>(
6,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'keepCheckpointEveryNHours',
$pb.PbFieldType.OF)
..e<SaverDef_CheckpointFormatVersion>(
7,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'version',
$pb.PbFieldType.OE,
defaultOrMaker: SaverDef_CheckpointFormatVersion.LEGACY,
valueOf: SaverDef_CheckpointFormatVersion.valueOf,
enumValues: SaverDef_CheckpointFormatVersion.values)
..hasRequiredFields = false;
SaverDef._() : super();
factory SaverDef({
$core.String? filenameTensorName,
$core.String? saveTensorName,
$core.String? restoreOpName,
$core.int? maxToKeep,
$core.bool? sharded,
$core.double? keepCheckpointEveryNHours,
SaverDef_CheckpointFormatVersion? version,
}) {
final _result = create();
if (filenameTensorName != null) {
_result.filenameTensorName = filenameTensorName;
}
if (saveTensorName != null) {
_result.saveTensorName = saveTensorName;
}
if (restoreOpName != null) {
_result.restoreOpName = restoreOpName;
}
if (maxToKeep != null) {
_result.maxToKeep = maxToKeep;
}
if (sharded != null) {
_result.sharded = sharded;
}
if (keepCheckpointEveryNHours != null) {
_result.keepCheckpointEveryNHours = keepCheckpointEveryNHours;
}
if (version != null) {
_result.version = version;
}
return _result;
}
factory SaverDef.fromBuffer($core.List<$core.int> i,
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) =>
create()..mergeFromBuffer(i, r);
factory SaverDef.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')
SaverDef clone() => SaverDef()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
SaverDef copyWith(void Function(SaverDef) updates) =>
super.copyWith((message) => updates(message as SaverDef))
as SaverDef; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline')
static SaverDef create() => SaverDef._();
SaverDef createEmptyInstance() => create();
static $pb.PbList<SaverDef> createRepeated() => $pb.PbList<SaverDef>();
@$core.pragma('dart2js:noInline')
static SaverDef getDefault() =>
_defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<SaverDef>(create);
static SaverDef? _defaultInstance;
@$pb.TagNumber(1)
$core.String get filenameTensorName => $_getSZ(0);
@$pb.TagNumber(1)
set filenameTensorName($core.String v) {
$_setString(0, v);
}
@$pb.TagNumber(1)
$core.bool hasFilenameTensorName() => $_has(0);
@$pb.TagNumber(1)
void clearFilenameTensorName() => clearField(1);
@$pb.TagNumber(2)
$core.String get saveTensorName => $_getSZ(1);
@$pb.TagNumber(2)
set saveTensorName($core.String v) {
$_setString(1, v);
}
@$pb.TagNumber(2)
$core.bool hasSaveTensorName() => $_has(1);
@$pb.TagNumber(2)
void clearSaveTensorName() => clearField(2);
@$pb.TagNumber(3)
$core.String get restoreOpName => $_getSZ(2);
@$pb.TagNumber(3)
set restoreOpName($core.String v) {
$_setString(2, v);
}
@$pb.TagNumber(3)
$core.bool hasRestoreOpName() => $_has(2);
@$pb.TagNumber(3)
void clearRestoreOpName() => clearField(3);
@$pb.TagNumber(4)
$core.int get maxToKeep => $_getIZ(3);
@$pb.TagNumber(4)
set maxToKeep($core.int v) {
$_setSignedInt32(3, v);
}
@$pb.TagNumber(4)
$core.bool hasMaxToKeep() => $_has(3);
@$pb.TagNumber(4)
void clearMaxToKeep() => clearField(4);
@$pb.TagNumber(5)
$core.bool get sharded => $_getBF(4);
@$pb.TagNumber(5)
set sharded($core.bool v) {
$_setBool(4, v);
}
@$pb.TagNumber(5)
$core.bool hasSharded() => $_has(4);
@$pb.TagNumber(5)
void clearSharded() => clearField(5);
@$pb.TagNumber(6)
$core.double get keepCheckpointEveryNHours => $_getN(5);
@$pb.TagNumber(6)
set keepCheckpointEveryNHours($core.double v) {
$_setFloat(5, v);
}
@$pb.TagNumber(6)
$core.bool hasKeepCheckpointEveryNHours() => $_has(5);
@$pb.TagNumber(6)
void clearKeepCheckpointEveryNHours() => clearField(6);
@$pb.TagNumber(7)
SaverDef_CheckpointFormatVersion get version => $_getN(6);
@$pb.TagNumber(7)
set version(SaverDef_CheckpointFormatVersion v) {
setField(7, v);
}
@$pb.TagNumber(7)
$core.bool hasVersion() => $_has(6);
@$pb.TagNumber(7)
void clearVersion() => clearField(7);
}
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/protobuf/saver.pb.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow/core/protobuf/saver.pb.dart",
"repo_id": "codelabs",
"token_count": 2813
} | 101 |
///
// Generated code. Do not modify.
// source: tensorflow_serving/apis/inference.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/tensorflow_serving/apis/inference.pbenum.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/inference.pbenum.dart",
"repo_id": "codelabs",
"token_count": 117
} | 102 |
///
// Generated code. Do not modify.
// source: tensorflow_serving/apis/regression.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/tensorflow_serving/apis/regression.pbenum.dart/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/generated/tensorflow_serving/apis/regression.pbenum.dart",
"repo_id": "codelabs",
"token_count": 117
} | 103 |
syntax = "proto3";
package tensorflow;
option cc_enable_arenas = true;
option java_outer_classname = "VariableProtos";
option java_multiple_files = true;
option java_package = "org.tensorflow.framework";
option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/variable_go_proto";
// Indicates when a distributed variable will be synced.
enum VariableSynchronization {
// `AUTO`: Indicates that the synchronization will be determined by the
// current `DistributionStrategy` (eg. With `MirroredStrategy` this would be
// `ON_WRITE`).
VARIABLE_SYNCHRONIZATION_AUTO = 0;
// `NONE`: Indicates that there will only be one copy of the variable, so
// there is no need to sync.
VARIABLE_SYNCHRONIZATION_NONE = 1;
// `ON_WRITE`: Indicates that the variable will be updated across devices
// every time it is written.
VARIABLE_SYNCHRONIZATION_ON_WRITE = 2;
// `ON_READ`: Indicates that the variable will be aggregated across devices
// when it is read (eg. when checkpointing or when evaluating an op that uses
// the variable).
VARIABLE_SYNCHRONIZATION_ON_READ = 3;
}
// Indicates how a distributed variable will be aggregated.
enum VariableAggregation {
// `NONE`: This is the default, giving an error if you use a
// variable-update operation with multiple replicas.
VARIABLE_AGGREGATION_NONE = 0;
// `SUM`: Add the updates across replicas.
VARIABLE_AGGREGATION_SUM = 1;
// `MEAN`: Take the arithmetic mean ("average") of the updates across
// replicas.
VARIABLE_AGGREGATION_MEAN = 2;
// `ONLY_FIRST_REPLICA`: This is for when every replica is performing the same
// update, but we only want to perform the update once. Used, e.g., for the
// global step counter.
VARIABLE_AGGREGATION_ONLY_FIRST_REPLICA = 3;
}
// Protocol buffer representing a Variable.
message VariableDef {
// Name of the variable tensor.
string variable_name = 1;
// Name of the tensor holding the variable's initial value.
string initial_value_name = 6;
// Name of the initializer op.
string initializer_name = 2;
// Name of the snapshot tensor.
string snapshot_name = 3;
// Support for saving variables as slices of a larger variable.
SaveSliceInfoDef save_slice_info_def = 4;
// Whether to represent this as a ResourceVariable.
bool is_resource = 5;
// Whether this variable should be trained.
bool trainable = 7;
// Indicates when a distributed variable will be synced.
VariableSynchronization synchronization = 8;
// Indicates how a distributed variable will be aggregated.
VariableAggregation aggregation = 9;
}
message SaveSliceInfoDef {
// Name of the full variable of which this is a slice.
string full_name = 1;
// Shape of the full variable.
repeated int64 full_shape = 2;
// Offset of this variable into the full variable.
repeated int64 var_offset = 3;
// Shape of this variable.
repeated int64 var_shape = 4;
}
| codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow/core/framework/variable.proto/0 | {
"file_path": "codelabs/tfserving-flutter/codelab2/starter/lib/proto/tensorflow/core/framework/variable.proto",
"repo_id": "codelabs",
"token_count": 902
} | 104 |
name: codelab_rebuild
description: A sample command-line application.
version: 1.0.0
# homepage: https://www.example.com
environment:
sdk: ^3.2.0
dependencies:
checked_yaml: ^2.0.1
io: ^1.0.3
json_annotation: ^4.8.0
logging: ^1.0.2
path: ^1.8.0
dev_dependencies:
build_runner: ^2.3.3
json_serializable: ^6.5.4
lints: ">=2.0.0 <4.0.0"
test: ^1.16.0
executables:
codelab_rebuild:
| codelabs/tooling/codelab_rebuild/pubspec.yaml/0 | {
"file_path": "codelabs/tooling/codelab_rebuild/pubspec.yaml",
"repo_id": "codelabs",
"token_count": 192
} | 105 |
#import "GeneratedPluginRegistrant.h"
| codelabs/webview_flutter/step_04/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/webview_flutter/step_04/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 106 |
#import "GeneratedPluginRegistrant.h"
| codelabs/webview_flutter/step_05/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/webview_flutter/step_05/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 107 |
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
| devtools/case_study/code_size/optimized/code_size_package/android/gradle.properties/0 | {
"file_path": "devtools/case_study/code_size/optimized/code_size_package/android/gradle.properties",
"repo_id": "devtools",
"token_count": 39
} | 108 |
#include "ephemeral/Flutter-Generated.xcconfig"
| devtools/case_study/code_size/unoptimized/code_size_images/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "devtools/case_study/code_size/unoptimized/code_size_images/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "devtools",
"token_count": 19
} | 109 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| devtools/case_study/code_size/unoptimized/code_size_package/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "devtools/case_study/code_size/unoptimized/code_size_package/macos/Runner/Configs/Release.xcconfig",
"repo_id": "devtools",
"token_count": 32
} | 110 |
include: package:flutter_lints/flutter.yaml
| devtools/case_study/memory_leaks/images_1/analysis_options.yaml/0 | {
"file_path": "devtools/case_study/memory_leaks/images_1/analysis_options.yaml",
"repo_id": "devtools",
"token_count": 16
} | 111 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| devtools/case_study/memory_leaks/images_1/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "devtools/case_study/memory_leaks/images_1/macos/Runner/Configs/Release.xcconfig",
"repo_id": "devtools",
"token_count": 32
} | 112 |
include: package:flutter_lints/flutter.yaml
| devtools/case_study/memory_leaks/leaking_counter_1/analysis_options.yaml/0 | {
"file_path": "devtools/case_study/memory_leaks/leaking_counter_1/analysis_options.yaml",
"repo_id": "devtools",
"token_count": 16
} | 113 |
buildscript {
ext.kotlin_version = '1.6.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.1.2'
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')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
| devtools/case_study/memory_leaks/leaking_counter_1/android/build.gradle/0 | {
"file_path": "devtools/case_study/memory_leaks/leaking_counter_1/android/build.gradle",
"repo_id": "devtools",
"token_count": 258
} | 114 |
// 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leaking_counter_1/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 our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| devtools/case_study/memory_leaks/leaking_counter_1/test/widget_test.dart/0 | {
"file_path": "devtools/case_study/memory_leaks/leaking_counter_1/test/widget_test.dart",
"repo_id": "devtools",
"token_count": 335
} | 115 |
// 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:flutter/material.dart';
import '../logging.dart';
import '../restful_servers.dart';
import 'http_data.dart';
class Settings extends StatefulWidget {
Settings() : restfulRoot = currentRestfulAPI;
final Logging logs = Logging.logging;
static late final SettingsState state;
final RestfulAPI restfulRoot;
@override
State<Settings> createState() {
state = SettingsState();
return state;
}
SettingsState get currentState => state;
}
/// Which Restful Server is selected.
String restfulApi = StarWars.starWarsPeople;
late RestfulAPI currentRestfulAPI;
class SettingsState extends State<Settings> {
Map<String, IconData> values = {
'${CitiBikesNYC.friendlyName}': Icons.directions_bike,
'${StarWars.starWarsFilms}': Icons.videocam,
'${StarWars.starWarsPeople}': Icons.people_outline,
'${StarWars.starWarsPlanets}': Icons.bubble_chart,
'${StarWars.starWarsSpecies}': Icons.android,
'${StarWars.starWarsStarships}': Icons.tram,
'${StarWars.starWarsVehicles}': Icons.time_to_leave,
'${OpenWeatherMapAPI.friendlyName}': Icons.cloud,
};
final Logging logs = Logging.logging;
@override
Widget build(BuildContext context) {
return Scaffold(
//appBar: AppBar(title: const Text('Restful Servers')),
body: ListView(
children: values.keys.map((String key) {
return ListTile(
leading: Icon(values[key]), // starships
title: Text(key),
trailing: const Icon(Icons.arrow_right),
onTap: () {
logs.add('$key Selected');
setState(() {
restfulApi = key;
});
// Display the data received.
unawaited(
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyGetHttpData()),
),
);
},
);
}).toList(),
),
);
}
}
| devtools/case_study/memory_leaks/memory_leak_app/lib/tabs/settings.dart/0 | {
"file_path": "devtools/case_study/memory_leaks/memory_leak_app/lib/tabs/settings.dart",
"repo_id": "devtools",
"token_count": 905
} | 116 |
---
redirect_to: https://flutter.dev/docs/development/tools/devtools/cli
---
| devtools/docs/cli.md/0 | {
"file_path": "devtools/docs/cli.md",
"repo_id": "devtools",
"token_count": 27
} | 117 |
retry: 3
| devtools/packages/devtools_app/dart_test.yaml/0 | {
"file_path": "devtools/packages/devtools_app/dart_test.yaml",
"repo_id": "devtools",
"token_count": 5
} | 118 |
// 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/devtools_app.dart';
import 'package:devtools_app/src/screens/debugger/breakpoints.dart';
import 'package:devtools_app/src/screens/debugger/call_stack.dart';
import 'package:devtools_app/src/screens/debugger/codeview.dart';
import 'package:devtools_app/src/service/service_extension_widgets.dart';
import 'package:devtools_test/helpers.dart';
import 'package:devtools_test/integration_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
// To run the test while connected to a flutter-tester device:
// dart run integration_test/run_tests.dart --target=integration_test/test/live_connection/debugger_panel_test.dart
// To run the test while connected to a chrome device:
// dart run integration_test/run_tests.dart --target=integration_test/test/live_connection/debugger_panel_test.dart --test-app-device=chrome
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
late TestApp testApp;
setUpAll(() {
testApp = TestApp.fromEnvironment();
expect(testApp.vmServiceUri, isNotNull);
});
testWidgets('Debugger panel', (tester) async {
await pumpAndConnectDevTools(tester, testApp);
await switchToScreen(
tester,
tabIcon: ScreenMetaData.debugger.icon!,
screenId: ScreenMetaData.debugger.id,
);
await tester.pump(safePumpDuration);
logStatus('looking for the main.dart file');
// Look for the main.dart file name:
expect(find.text('package:flutter_app/main.dart'), findsOneWidget);
// Look for the main.dart source code:
final firstLineFinder = findLineItemWithText('FILE: main.dart');
expect(firstLineFinder, findsOneWidget);
// Look for the first gutter item:
final firstGutterFinder = findGutterItemWithText('1');
expect(firstGutterFinder, findsOneWidget);
// Verify that the gutter item and line item are aligned:
expect(
areHorizontallyAligned(
firstGutterFinder,
firstLineFinder,
tester: tester,
),
isTrue,
);
logStatus('Navigating to line 57...');
await goToLine(tester, lineNumber: 57);
logStatus('looking for line 57');
// Look for the line 57 gutter item:
final gutter57Finder = findGutterItemWithText('57');
expect(gutter57Finder, findsOneWidget);
// Look for the line 57 line item:
final line57Finder = findLineItemWithText("print('Hello!');");
expect(line57Finder, findsOneWidget);
// Verify that the gutter item and line item are aligned:
expect(
areHorizontallyAligned(
gutter57Finder,
line57Finder,
tester: tester,
),
isTrue,
);
logStatus('setting a breakpoint');
// Tap on the gutter for the line to set a breakpoint:
await tester.tap(gutter57Finder);
await tester.pumpAndSettle(longPumpDuration);
logStatus('performing a hot restart');
await tester.tap(find.byType(HotRestartButton));
await tester.pumpAndSettle(longPumpDuration);
logStatus('Navigating to line 30...');
await goToLine(tester, lineNumber: 30);
logStatus('looking for line 30');
// Look for the line 30 gutter item:
final gutter30Finder = findGutterItemWithText('30');
expect(gutter30Finder, findsOneWidget);
// Look for the line 30 line item:
final line30Finder = findLineItemWithText('count++;');
expect(line30Finder, findsOneWidget);
// Verify that the gutter item and line item are aligned:
expect(
areHorizontallyAligned(
gutter30Finder,
line30Finder,
tester: tester,
),
isTrue,
);
logStatus('setting a breakpoint');
// Tap on the gutter for the line to set a breakpoint:
await tester.tap(gutter30Finder);
await tester.pumpAndSettle(longPumpDuration);
logStatus('verifying breakpoints');
final bpSetBeforeRestart = findBreakpointWithText('main.dart:57');
expect(bpSetBeforeRestart, findsOneWidget);
logStatus('pausing at breakpoint');
final topFrameFinder = findStackFrameWithText('incrementCounter');
expect(topFrameFinder, findsOneWidget);
expect(isLineFocused(line30Finder), isTrue);
final countVariableFinder = find.textContaining('count:');
expect(countVariableFinder, findsOneWidget);
logStatus('inspecting variables');
final callingFrameFinder = findStackFrameWithText('<closure>');
expect(callingFrameFinder, findsOneWidget);
logStatus('switching stackframes');
// Tap on the stackframe:
await tester.tap(callingFrameFinder);
await tester.pumpAndSettle(safePumpDuration);
logStatus('looking for the other_classes.dart file');
expect(
find.text('package:flutter_app/src/other_classes.dart'),
findsOneWidget,
);
logStatus('looking for the focused line');
// Look for the line 46 gutter item:
final gutter46Finder = findGutterItemWithText('46');
expect(gutter46Finder, findsOneWidget);
// Look for the line 46 line item:
final line46Finder = findLineItemWithText('_action();');
expect(line46Finder, findsOneWidget);
// Verify that the gutter item and line item are aligned:
expect(
areHorizontallyAligned(
gutter46Finder,
line46Finder,
tester: tester,
),
isTrue,
);
// Verify that line 46 is focused:
expect(isLineFocused(line46Finder), isTrue);
});
}
bool areHorizontallyAligned(
Finder widgetAFinder,
Finder widgetBFinder, {
required WidgetTester tester,
}) {
final widgetACenter = tester.getCenter(widgetAFinder);
final widgetBCenter = tester.getCenter(widgetBFinder);
return widgetACenter.dy == widgetBCenter.dy;
}
Future<void> goToLine(WidgetTester tester, {required int lineNumber}) async {
logStatus('opening the "more" menu');
final moreMenuFinder = find.byType(PopupMenuButton<ScriptPopupMenuOption>);
expect(moreMenuFinder, findsOneWidget);
await tester.tap(moreMenuFinder);
await tester.pumpAndSettle(safePumpDuration);
logStatus('selecting the go-to-line menu option');
final goToLineOptionFinder = find.textContaining('Go to line number');
expect(goToLineOptionFinder, findsOneWidget);
await tester.tap(goToLineOptionFinder);
await tester.pumpAndSettle(safePumpDuration);
logStatus('entering line number $lineNumber in the go-to-line dialog');
final goToLineInputFinder = find.widgetWithText(TextField, 'Line Number');
expect(goToLineInputFinder, findsOneWidget);
await tester.enterText(goToLineInputFinder, '$lineNumber');
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pumpAndSettle(safePumpDuration);
}
T getWidgetFromFinder<T>(Finder finder) =>
finder.first.evaluate().first.widget as T;
Finder findLineItemWithText(String text) => find.ancestor(
of: find.textContaining(text),
matching: find.byType(LineItem),
);
Finder findGutterItemWithText(String text) => find.ancestor(
of: find.text(text),
matching: find.byType(GutterItem),
);
bool isLineFocused(Finder lineItemFinder) {
final lineWidget = getWidgetFromFinder<LineItem>(lineItemFinder);
return lineWidget.focused;
}
Finder findStackFrameWithText(String text) => find.descendant(
of: find.byType(CallStack),
matching: find.richTextContaining(text),
);
Finder findBreakpointWithText(String text) => find.descendant(
of: find.byType(Breakpoints),
matching: find.richTextContaining(text),
);
| devtools/packages/devtools_app/integration_test/test/live_connection/debugger_panel_test.dart/0 | {
"file_path": "devtools/packages/devtools_app/integration_test/test/live_connection/debugger_panel_test.dart",
"repo_id": "devtools",
"token_count": 2727
} | 119 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.