code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
// Copyright (c) 2015, 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 'dart:isolate'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:source_span/source_span.dart'; import '../util/package_config.dart'; import 'string_literal_iterator.dart'; /// Runs [code] in an isolate. /// /// [code] should be the contents of a Dart entrypoint. It may contain imports; /// they will be resolved in the same context as the host isolate. [message] is /// passed to the [main] method of the code being run; the caller is responsible /// for using this to establish communication with the isolate. Future<Isolate> runInIsolate(String code, Object message, {SendPort? onExit}) async => Isolate.spawnUri( Uri.dataFromString(code, mimeType: 'application/dart', encoding: utf8), [], message, packageConfig: await packageConfigUri, checked: true, onExit: onExit); /// Takes a span whose source is the value of a string that has been parsed from /// a Dart file and returns the corresponding span from within that Dart file. /// /// For example, suppose a Dart file contains `@Eval("1 + a")`. The /// [StringLiteral] `"1 + a"` is extracted; this is [context]. Its contents are /// then parsed, producing an error pointing to [span]: /// /// line 1, column 5: /// 1 + a /// ^ /// /// This span isn't very useful, since it only shows the location within the /// [StringLiteral]'s value. So it's passed to [contextualizeSpan] along with /// [context] and [file] (which contains the source of the entire Dart file), /// which then returns: /// /// line 4, column 12 of file.dart: /// @Eval("1 + a") /// ^ /// /// This properly handles multiline literals, adjacent literals, and literals /// containing escape sequences. It does not support interpolated literals. /// /// This will return `null` if [context] contains an invalid string or does not /// contain [span]. SourceSpan? contextualizeSpan( SourceSpan span, StringLiteral context, SourceFile file) { var contextRunes = StringLiteralIterator(context)..moveNext(); for (var i = 0; i < span.start.offset; i++) { if (!contextRunes.moveNext()) return null; } var start = contextRunes.offset; for (var spanRune in span.text.runes) { if (spanRune != contextRunes.current) return null; contextRunes.moveNext(); } return file.span(start, contextRunes.offset); } /// Parses and returns the currently enabled experiments from /// [Platform.executableArguments]. final List<String> enabledExperiments = () { var experiments = <String>[]; var itr = Platform.executableArguments.iterator; while (itr.moveNext()) { var arg = itr.current; if (arg == '--enable-experiment') { if (!itr.moveNext()) break; experiments.add(itr.current); } else if (arg.startsWith('--enable-experiment=')) { var parts = arg.split('='); if (parts.length == 2) { experiments.addAll(parts[1].split(',')); } } } return experiments; }();
test/pkgs/test_core/lib/src/util/dart.dart/0
{'file_path': 'test/pkgs/test_core/lib/src/util/dart.dart', 'repo_id': 'test', 'token_count': 1072}
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class SuedeTextureRenderObject extends RenderProxyBox { @override bool hitTestSelf(Offset position) => true; @override void paint(PaintingContext context, Offset offset) { context.canvas.save(); context.canvas.translate(offset.dx, offset.dy); final basePaint = Paint() ..color = Colors.brown[400]! // Base color of the suede ..style = PaintingStyle.fill; // Fill the canvas with the base color context.canvas.drawRect(offset & size, basePaint); final random = Random(0); // Apply a noise pattern to create a napped surface appearance final noisePaint = Paint()..strokeWidth = 1; for (var i = 0; i < 10000; i++) { final x = random.nextDouble() * size.width; final y = random.nextDouble() * size.height; final opacity = random.nextDouble() * 0.5; noisePaint.color = Colors.brown.withOpacity(opacity); // Using drawCircle to simulate a point context.canvas.drawCircle(Offset(x, y), 1, noisePaint); } context.canvas.restore(); super.paint(context, offset); } }
textura/lib/src/textures/fabrics/suede.dart/0
{'file_path': 'textura/lib/src/textures/fabrics/suede.dart', 'repo_id': 'textura', 'token_count': 417}
import 'dart:math'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class GraffitiTextureRenderObject extends RenderProxyBox { @override bool hitTestSelf(Offset position) => true; @override void paint(PaintingContext context, Offset offset) { context.canvas.save(); context.canvas.translate(offset.dx, offset.dy); final random = Random(0); final graffitiPaint = Paint() ..color = Colors.black ..style = PaintingStyle.stroke ..strokeWidth = 4; const numberOfLines = 10; // Drawing graffiti lines and curves for (var i = 0; i < numberOfLines; i++) { final startX = random.nextDouble() * size.width; final startY = random.nextDouble() * size.height; final endX = random.nextDouble() * size.width; final endY = random.nextDouble() * size.height; final controlPointX = random.nextDouble() * size.width; final controlPointY = random.nextDouble() * size.height; context.canvas .drawLine(Offset(startX, startY), Offset(endX, endY), graffitiPaint); context.canvas.drawPoints( PointMode.points, [Offset(controlPointX, controlPointY)], graffitiPaint..strokeCap = StrokeCap.round, ); } context.canvas.restore(); super.paint(context, offset); } }
textura/lib/src/textures/miscellaneous/graffiti.dart/0
{'file_path': 'textura/lib/src/textures/miscellaneous/graffiti.dart', 'repo_id': 'textura', 'token_count': 505}
import 'dart:math'; import 'package:flutter/rendering.dart'; class SandTextureRenderObject extends RenderProxyBox { final Random _random = Random(); @override void paint(PaintingContext context, Offset offset) { super.paint(context, offset); final canvas = context.canvas; const numGrains = 2000; final sandPaint = Paint()..strokeCap = StrokeCap.round; for (var i = 0; i < numGrains; i++) { final sandX = _random.nextDouble() * size.width; final sandY = _random.nextDouble() * size.height; final sandRadius = _random.nextDouble() * 1.5; final brownBase = 100 + _random.nextInt(50); sandPaint.color = Color.fromRGBO( brownBase + 50, brownBase, brownBase - 50, _random.nextDouble(), ); canvas.drawCircle( Offset(sandX + offset.dx, sandY + offset.dy), sandRadius, sandPaint, ); } } }
textura/lib/src/textures/nature/sand.dart/0
{'file_path': 'textura/lib/src/textures/nature/sand.dart', 'repo_id': 'textura', 'token_count': 379}
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class ZebraTextureRenderObject extends RenderProxyBox { @override bool hitTestSelf(Offset position) => true; @override void paint(PaintingContext context, Offset offset) { context.canvas.save(); context.canvas.translate(offset.dx, offset.dy); final whitePaint = Paint() ..color = Colors.white ..style = PaintingStyle.fill; final blackPaint = Paint() ..color = Colors.black ..style = PaintingStyle.fill; // Drawing the zebra stripes for (var i = 0; i < size.height; i += 20) { final isWhite = (i ~/ 20).isEven; final waveHeight = sin(i / 20) * 10; final paint = isWhite ? whitePaint : blackPaint; context.canvas.drawRect( Rect.fromPoints( Offset(0, i.toDouble() + waveHeight), Offset(size.width, i.toDouble() + 20 + waveHeight), ), paint, ); } context.canvas.restore(); super.paint(context, offset); } }
textura/lib/src/textures/patterns/zebra.dart/0
{'file_path': 'textura/lib/src/textures/patterns/zebra.dart', 'repo_id': 'textura', 'token_count': 421}
import 'package:three_dart/three3d/extras/core/curve.dart'; import 'package:three_dart/three3d/extras/curves/line_curve.dart'; /// ************************************************************ /// Curved Path - a curve path is simply a array of connected /// curves, but retains the api of a curve ///*************************************************************/ class CurvePath extends Curve { CurvePath() : super() { type = 'CurvePath'; curves = []; autoClose = false; // Automatically closes the path } CurvePath.fromJSON(Map<String, dynamic> json) : super.fromJSON(json) { autoClose = json["autoClose"]; type = 'CurvePath'; curves = []; for (var i = 0, l = json["curves"].length; i < l; i++) { var curve = json["curves"][i]; curves.add(Curve.castJSON(curve)); } } add(Curve curve) { curves.add(curve); } closePath() { // Add a line curve if start and end of lines are not connected var startPoint = curves[0].getPoint(0, null); var endPoint = curves[curves.length - 1].getPoint(1, null); if (!startPoint.equals(endPoint)) { curves.add(LineCurve(endPoint, startPoint)); } } // To get accurate point with reference to // entire path distance at time t, // following has to be done: // 1. Length of each sub path have to be known // 2. Locate and identify type of curve // 3. Get t for the curve // 4. Return curve.getPointAt(t') @override getPoint(t, optionalTarget) { var d = t * getLength(); var curveLengths = getCurveLengths(); var i = 0; // To think about boundaries points. while (i < curveLengths.length) { if (curveLengths[i] >= d) { var diff = curveLengths[i] - d; var curve = curves[i]; var segmentLength = curve.getLength(); var u = segmentLength == 0 ? 0 : 1 - diff / segmentLength; return curve.getPointAt(u, optionalTarget); } i++; } return null; // loop where sum != 0, sum > d , sum+1 <d } // We cannot use the default three.Curve getPoint() with getLength() because in // three.Curve, getLength() depends on getPoint() but in three.CurvePath // getPoint() depends on getLength @override getLength() { var lens = getCurveLengths(); return lens[lens.length - 1]; } // cacheLengths must be recalculated. @override updateArcLengths() { needsUpdate = true; cacheLengths = null; getCurveLengths(); } // Compute lengths and cache them // We cannot overwrite getLengths() because UtoT mapping uses it. List<num> getCurveLengths() { // We use cache values if curves and cache array are same length if (cacheLengths != null && cacheLengths!.length == curves.length) { return cacheLengths!; } // Get length of sub-curve // Push sums into cached array List<num> lengths = []; num sums = 0.0; for (var i = 0, l = curves.length; i < l; i++) { sums += curves[i].getLength(); lengths.add(sums); } cacheLengths = lengths; return lengths; } @override getSpacedPoints([num divisions = 40, num offset = 0.0]) { var points = []; for (var i = 0; i <= divisions; i++) { var offset2 = offset + i / divisions; if (offset2 > 1.0) { offset2 = offset2 - 1.0; } points.add(getPoint(offset2, null)); } if (autoClose) { points.add(points[0]); } return points; } @override List getPoints([num divisions = 12]) { var points = []; var last; for (var i = 0, curves = this.curves; i < curves.length; i++) { var curve = curves[i]; var resolution = (curve.isEllipseCurve) ? divisions * 2 : ((curve is LineCurve || curve is LineCurve3)) ? 1 : (curve.isSplineCurve) ? divisions * curve.points.length : divisions; var pts = curve.getPoints(resolution); for (var j = 0; j < pts.length; j++) { var point = pts[j]; if (last != null && last.equals(point)) { continue; } // ensures no consecutive points are duplicates points.add(point); last = point; } } if (autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) { points.add(points[0]); } return points; } @override copy(source) { super.copy(source); curves = []; for (var i = 0, l = source.curves.length; i < l; i++) { var curve = source.curves[i]; curves.add(curve.clone()); } autoClose = source.autoClose; return this; } @override toJSON() { var data = super.toJSON(); data["autoClose"] = autoClose; data["curves"] = []; for (var i = 0, l = curves.length; i < l; i++) { var curve = curves[i]; data["curves"].add(curve.toJSON()); } return data; } }
three_dart/lib/three3d/extras/core/curve_path.dart/0
{'file_path': 'three_dart/lib/three3d/extras/core/curve_path.dart', 'repo_id': 'three_dart', 'token_count': 1929}
import 'package:flutter_gl/flutter_gl.dart'; import 'package:three_dart/three3d/core/index.dart'; import 'package:three_dart/three3d/math/index.dart'; class ParametricGeometry extends BufferGeometry { ParametricGeometry(func, slices, stacks) : super() { type = "ParametricGeometry"; parameters = {"func": func, "slices": slices, "stacks": stacks}; // buffers List<num> indices = []; List<double> vertices = []; List<double> normals = []; List<double> uvs = []; var eps = 0.00001; var normal = Vector3(); var p0 = Vector3(), p1 = Vector3(); var pu = Vector3(), pv = Vector3(); // if ( func.length < 3 ) { // print( 'three.ParametricGeometry: Function must now modify a Vector3 as third parameter.' ); // } // generate vertices, normals and uvs var sliceCount = slices + 1; for (var i = 0; i <= stacks; i++) { var v = i / stacks; for (var j = 0; j <= slices; j++) { var u = j / slices; // vertex func(u, v, p0); vertices.addAll([p0.x.toDouble(), p0.y.toDouble(), p0.z.toDouble()]); // normal // approximate tangent vectors via finite differences if (u - eps >= 0) { func(u - eps, v, p1); pu.subVectors(p0, p1); } else { func(u + eps, v, p1); pu.subVectors(p1, p0); } if (v - eps >= 0) { func(u, v - eps, p1); pv.subVectors(p0, p1); } else { func(u, v + eps, p1); pv.subVectors(p1, p0); } // cross product of tangent vectors returns surface normal normal.crossVectors(pu, pv).normalize(); normals.addAll([normal.x.toDouble(), normal.y.toDouble(), normal.z.toDouble()]); // uv uvs.addAll([u, v]); } } // generate indices for (var i = 0; i < stacks; i++) { for (var j = 0; j < slices; j++) { var a = i * sliceCount + j; var b = i * sliceCount + j + 1; var c = (i + 1) * sliceCount + j + 1; var d = (i + 1) * sliceCount + j; // faces one and two indices.addAll([a, b, d]); indices.addAll([b, c, d]); } } // build geometry setIndex(indices); setAttribute('position', Float32BufferAttribute(Float32Array.from(vertices), 3)); setAttribute('normal', Float32BufferAttribute(Float32Array.from(normals), 3)); setAttribute('uv', Float32BufferAttribute(Float32Array.from(uvs), 2)); } }
three_dart/lib/three3d/geometries/parametric_geometry.dart/0
{'file_path': 'three_dart/lib/three3d/geometries/parametric_geometry.dart', 'repo_id': 'three_dart', 'token_count': 1132}
library lights; export 'ambient_light.dart'; export 'directional_light.dart'; export 'directional_light_shadow.dart'; export 'hemisphere_light.dart'; export 'hemisphere_light_probe.dart'; export 'light.dart'; export 'light_probe.dart'; export 'light_shadow.dart'; export 'point_light.dart'; export 'point_light_shadow.dart'; export 'rect_area_light.dart'; export 'spot_light.dart'; export 'spot_light_shadow.dart';
three_dart/lib/three3d/lights/index.dart/0
{'file_path': 'three_dart/lib/three3d/lights/index.dart', 'repo_id': 'three_dart', 'token_count': 150}
import 'dart:async'; import 'package:three_dart/extra/blob.dart'; import 'dart:html' as html; class ImageLoaderLoader { // flipY 在web环境下 忽略 static Future<html.ImageElement> loadImage(url, flipY, {Function? imageDecoder}) { var completer = Completer<html.ImageElement>(); var imageDom = html.ImageElement(); imageDom.crossOrigin = ""; imageDom.onLoad.listen((e) { completer.complete(imageDom); }); if (url is Blob) { var blob = html.Blob([url.data.buffer], url.options["type"]); imageDom.src = html.Url.createObjectUrl(blob); } else { // flutter web for assets need add assets TODO if (url.startsWith("assets")) { imageDom.src = "assets/$url"; } else { imageDom.src = url; } } return completer.future; } }
three_dart/lib/three3d/loaders/image_loader_for_web.dart/0
{'file_path': 'three_dart/lib/three3d/loaders/image_loader_for_web.dart', 'repo_id': 'three_dart', 'token_count': 341}
import 'package:three_dart/three3d/constants.dart'; import 'package:three_dart/three3d/materials/material.dart'; import 'package:three_dart/three3d/math/index.dart'; class MeshBasicMaterial extends Material { MeshBasicMaterial([Map<String, dynamic>? parameters]) : super() { type = 'MeshBasicMaterial'; color = Color(1, 1, 1); // emissive map = null; lightMap = null; lightMapIntensity = 1.0; aoMap = null; aoMapIntensity = 1.0; specularMap = null; alphaMap = null; // this.envMap = null; combine = MultiplyOperation; reflectivity = 1; refractionRatio = 0.98; wireframe = false; wireframeLinewidth = 1; wireframeLinecap = 'round'; wireframeLinejoin = 'round'; fog = true; setValues(parameters); } @override MeshBasicMaterial copy(Material source) { super.copy(source); color.copy(source.color); map = source.map; lightMap = source.lightMap; lightMapIntensity = source.lightMapIntensity; aoMap = source.aoMap; aoMapIntensity = source.aoMapIntensity; specularMap = source.specularMap; alphaMap = source.alphaMap; envMap = source.envMap; combine = source.combine; reflectivity = source.reflectivity; refractionRatio = source.refractionRatio; wireframe = source.wireframe; wireframeLinewidth = source.wireframeLinewidth; wireframeLinecap = source.wireframeLinecap; wireframeLinejoin = source.wireframeLinejoin; fog = source.fog; return this; } @override MeshBasicMaterial clone() { return MeshBasicMaterial().copy(this); } }
three_dart/lib/three3d/materials/mesh_basic_material.dart/0
{'file_path': 'three_dart/lib/three3d/materials/mesh_basic_material.dart', 'repo_id': 'three_dart', 'token_count': 601}
library objects; export 'bone.dart'; export 'group.dart'; export 'instanced_mesh.dart'; export 'line.dart'; export 'line_loop.dart'; export 'line_segments.dart'; export 'mesh.dart'; export 'points.dart'; export 'skeleton.dart'; export 'skinned_mesh.dart'; export 'sprite.dart';
three_dart/lib/three3d/objects/index.dart/0
{'file_path': 'three_dart/lib/three3d/objects/index.dart', 'repo_id': 'three_dart', 'token_count': 108}
String alphatestFragment = """ #ifdef USE_ALPHATEST if ( diffuseColor.a < alphaTest ) discard; #endif """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/alphatest_fragment.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/alphatest_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 41}
String colorParsFragment = """ #if defined( USE_COLOR_ALPHA ) varying vec4 vColor; #elif defined( USE_COLOR ) varying vec3 vColor; #endif """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/color_pars_fragment.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/color_pars_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 60}
String envmapCommonParsFragment = """ #ifdef USE_ENVMAP uniform float envMapIntensity; uniform float flipEnvMap; #ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #else uniform sampler2D envMap; #endif #endif """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/envmap_common_pars_fragment.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/envmap_common_pars_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 93}
String mapParticleParsFragment = """ #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) uniform mat3 uvTransform; #endif #ifdef USE_MAP uniform sampler2D map; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/map_particle_pars_fragment.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/map_particle_pars_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 95}
String projectVertex = """ vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_INSTANCING mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition; """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/project_vertex.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/project_vertex.glsl.dart', 'repo_id': 'three_dart', 'token_count': 80}
String distanceRgbaVert = """ #define DISTANCE varying vec3 vWorldPosition; #include <common> #include <uv_pars_vertex> #include <displacementmap_pars_vertex> #include <morphtarget_pars_vertex> #include <skinning_pars_vertex> #include <clipping_planes_pars_vertex> void main() { #include <uv_vertex> #include <skinbase_vertex> #ifdef USE_DISPLACEMENTMAP #include <beginnormal_vertex> #include <morphnormal_vertex> #include <skinnormal_vertex> #endif #include <begin_vertex> #include <morphtarget_vertex> #include <skinning_vertex> #include <displacementmap_vertex> #include <project_vertex> #include <worldpos_vertex> #include <clipping_planes_vertex> vWorldPosition = worldPosition.xyz; } """;
three_dart/lib/three3d/renderers/shaders/shader_lib/distanceRGBA_vert.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_lib/distanceRGBA_vert.glsl.dart', 'repo_id': 'three_dart', 'token_count': 278}
import 'package:flutter_gl/flutter_gl.dart'; import 'package:three_dart/three3d/core/buffer_attribute.dart'; import 'package:three_dart/three3d/core/buffer_geometry.dart'; import 'package:three_dart/three3d/core/event_dispatcher.dart'; import 'package:three_dart/three3d/core/instanced_buffer_geometry.dart'; import 'package:three_dart/three3d/renderers/webgl/index.dart'; import 'package:three_dart/three3d/utils.dart'; import 'package:three_dart/three3d/weak_map.dart'; class WebGLGeometries { dynamic gl; WebGLAttributes attributes; WebGLInfo info; WebGLBindingStates bindingStates; Map<int, bool> geometries = {}; var wireframeAttributes = WeakMap(); WebGLGeometries(this.gl, this.attributes, this.info, this.bindingStates); void onGeometryDispose(Event event) { var geometry = event.target; if (geometry.index != null) { attributes.remove(geometry.index); } for (var name in geometry.attributes.keys) { attributes.remove(geometry.attributes[name]); } geometry.removeEventListener('dispose', onGeometryDispose); geometries.remove(geometry.id); var attribute = wireframeAttributes.get(geometry); if (attribute != null) { attributes.remove(attribute); wireframeAttributes.delete(geometry); } bindingStates.releaseStatesOfGeometry(geometry); if (geometry is InstancedBufferGeometry) { // geometry.remove("maxInstanceCount"); geometry.maxInstanceCount = null; } // info.memory["geometries"] = info.memory["geometries"]! - 1; } BufferGeometry get(object, BufferGeometry geometry) { if (geometries[geometry.id] == true) return geometry; geometry.addEventListener('dispose', onGeometryDispose); geometries[geometry.id] = true; info.memory["geometries"] = info.memory["geometries"]! + 1; return geometry; } void update(BufferGeometry geometry) { var geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates. for (var name in geometryAttributes.keys) { attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER, name: name); } // morph targets var morphAttributes = geometry.morphAttributes; for (var name in morphAttributes.keys) { var array = morphAttributes[name]!; for (var i = 0, l = array.length; i < l; i++) { attributes.update(array[i], gl.ARRAY_BUFFER, name: "$name - morphAttributes i: $i"); } } } void updateWireframeAttribute(BufferGeometry geometry) { List<int> indices = []; var geometryIndex = geometry.index; var geometryPosition = geometry.attributes["position"]; var version = 0; if (geometryIndex != null) { var array = geometryIndex.array; version = geometryIndex.version; for (var i = 0, l = array.length; i < l; i += 3) { var a = array[i + 0].toInt(); var b = array[i + 1].toInt(); var c = array[i + 2].toInt(); indices.addAll([a, b, b, c, c, a]); } } else { var array = geometryPosition.array; version = geometryPosition.version; for (var i = 0, l = (array.length / 3) - 1; i < l; i += 3) { var a = i + 0; var b = i + 1; var c = i + 2; indices.addAll([a, b, b, c, c, a]); } } BufferAttribute attribute; final max = arrayMax(indices); if (max != null && max > 65535) { attribute = Uint32BufferAttribute(Uint32Array.from(indices), 1, false); } else { attribute = Uint16BufferAttribute(Uint16Array.from(indices), 1, false); } attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates // var previousAttribute = wireframeAttributes.get(geometry); if (previousAttribute != null) attributes.remove(previousAttribute); // wireframeAttributes.add(key: geometry, value: attribute); } getWireframeAttribute(BufferGeometry geometry) { var currentAttribute = wireframeAttributes.get(geometry); if (currentAttribute != null) { var geometryIndex = geometry.index; if (geometryIndex != null) { // if the attribute is obsolete, create a new one if (currentAttribute.version < geometryIndex.version) { updateWireframeAttribute(geometry); } } } else { updateWireframeAttribute(geometry); } return wireframeAttributes.get(geometry); } void dispose() {} }
three_dart/lib/three3d/renderers/webgl/web_gl_geometries.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/webgl/web_gl_geometries.dart', 'repo_id': 'three_dart', 'token_count': 1658}
import 'package:three_dart/three3d/materials/index.dart'; int _id = 0; class WebGLShaderCache { var shaderCache = {}; var materialCache = {}; WebGLShaderCache(); WebGLShaderCache update(Material material) { var vertexShader = material.vertexShader; var fragmentShader = material.fragmentShader; var vertexShaderStage = _getShaderStage(vertexShader!); var fragmentShaderStage = _getShaderStage(fragmentShader!); var materialShaders = _getShaderCacheForMaterial(material); if (materialShaders.contains(vertexShaderStage) == false) { materialShaders.add(vertexShaderStage); vertexShaderStage.usedTimes++; } if (materialShaders.contains(fragmentShaderStage) == false) { materialShaders.add(fragmentShaderStage); fragmentShaderStage.usedTimes++; } return this; } WebGLShaderCache remove(Material material) { var materialShaders = materialCache[material]; for (var shaderStage in materialShaders) { shaderStage.usedTimes--; if (shaderStage.usedTimes == 0) shaderCache.remove(shaderStage.code); } materialCache.remove(material); return this; } getVertexShaderID(Material material) { return _getShaderStage(material.vertexShader!).id; } getFragmentShaderID(Material material) { return _getShaderStage(material.fragmentShader!).id; } void dispose() { shaderCache.clear(); materialCache.clear(); } _getShaderCacheForMaterial(Material material) { var cache = materialCache; if (cache.containsKey(material) == false) { cache[material] = []; } return cache[material]; } _getShaderStage(String code) { var cache = shaderCache; if (cache.containsKey(code) == false) { var stage = WebGLShaderStage(code); cache[code] = stage; } return cache[code]; } } class WebGLShaderStage { late int id; late int usedTimes; late String code; WebGLShaderStage(this.code) { id = _id++; usedTimes = 0; } }
three_dart/lib/three3d/renderers/webgl/web_gl_shader_cache.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/webgl/web_gl_shader_cache.dart', 'repo_id': 'three_dart', 'token_count': 738}
import 'package:flutter_gl/flutter_gl.dart'; import 'package:three_dart/three3d/textures/texture.dart'; import 'package:three_dart/three3d/textures/image_element.dart'; import 'package:three_dart/three3d/constants.dart'; class Data3DTexture extends Texture { bool isDataTexture3D = true; Data3DTexture([NativeArray? data, int width = 1, int height = 1, int depth = 1]) : super(null, null, null, null, null, null, null, null, null, null) { image = ImageElement(data: data, width: width, height: height, depth: depth); magFilter = LinearFilter; minFilter = LinearFilter; wrapR = ClampToEdgeWrapping; generateMipmaps = false; flipY = false; unpackAlignment = 1; } // We're going to add .setXXX() methods for setting properties later. // Users can still set in DataTexture3D directly. // // const texture = new three.DataTexture3D( data, width, height, depth ); // texture.anisotropy = 16; // // See #14839 }
three_dart/lib/three3d/textures/data_3d_texture.dart/0
{'file_path': 'three_dart/lib/three3d/textures/data_3d_texture.dart', 'repo_id': 'three_dart', 'token_count': 340}
library three_dart; export 'extensions/list_extension.dart'; export 'three3d/three.dart'; export 'extra/blob.dart';
three_dart/lib/three_dart.dart/0
{'file_path': 'three_dart/lib/three_dart.dart', 'repo_id': 'three_dart', 'token_count': 45}
part of tiled; /// Below is Tiled's documentation about how this structure is represented /// on XML files: /// /// <text> /// /// * fontfamily: The font family used (defaults to "sans-serif") /// * pixelsize: The size of the font in pixels (not using points, because /// other sizes in the TMX format are also using pixels) (defaults to 16) /// * wrap: Whether word wrapping is enabled (1) or disabled (0). /// (defaults to 0) /// * color: Color of the text in #AARRGGBB or #RRGGBB format /// (defaults to #000000) /// * bold: Whether the font is bold (1) or not (0). (defaults to 0) /// * italic: Whether the font is italic (1) or not (0). (defaults to 0) /// * underline: Whether a line should be drawn below the text (1) or not (0). /// (defaults to 0) /// * strikeout: Whether a line should be drawn through the text (1) or not (0). /// (defaults to 0) /// * kerning: Whether kerning should be used while rendering the text (1) or /// not (0). (defaults to 1) /// * halign: Horizontal alignment of the text within the object (left, center, /// right or justify, defaults to left) (since Tiled 1.2.1) /// * valign: Vertical alignment of the text within the object (top , center /// or bottom, defaults to top) /// /// Used to mark an object as a text object. Contains the actual text as /// character data. /// /// For alignment purposes, the bottom of the text is the descender height of /// the font, and the top of the text is the ascender height of the font. /// For example, bottom alignment of the word “cat” will leave some space below /// the text, even though it is unused for this word with most fonts. /// Similarly, top alignment of the word “cat” will leave some space above the /// "t" with most fonts, because this space is used for diacritics. /// /// If the text is larger than the object’s bounds, it is clipped to the bounds /// of the object. class Text { String fontFamily; int pixelSize; String color; String text; HAlign hAlign; VAlign vAlign; bool bold; bool italic; bool underline; bool strikeout; bool kerning; bool wrap; Text({ this.fontFamily = 'sans-serif', this.pixelSize = 16, this.color = '#000000', this.text = '', this.hAlign = HAlign.left, this.vAlign = VAlign.top, this.bold = false, this.italic = false, this.underline = false, this.strikeout = false, this.kerning = true, this.wrap = false, }); Text.parse(Parser parser) : this( fontFamily: parser.getString('fontFamily', defaults: 'sans-serif'), pixelSize: parser.getInt('pixelSize', defaults: 16), color: parser.getString('color', defaults: '#000000'), text: parser.getInnerTextOrNull() ?? parser.getString('text', defaults: ''), hAlign: parser.getHAlign('hAlign', defaults: HAlign.left), vAlign: parser.getVAlign('vAlign', defaults: VAlign.top), bold: parser.getBool('bold', defaults: false), italic: parser.getBool('italic', defaults: false), underline: parser.getBool('underline', defaults: false), strikeout: parser.getBool('strikeout', defaults: false), kerning: parser.getBool('kerning', defaults: true), wrap: parser.getBool('wrap', defaults: false), ); }
tiled.dart/packages/tiled/lib/src/objects/text.dart/0
{'file_path': 'tiled.dart/packages/tiled/lib/src/objects/text.dart', 'repo_id': 'tiled.dart', 'token_count': 1154}
import 'package:flutter_test/flutter_test.dart'; import 'package:tiled/tiled.dart'; void main() { group('ObjectAlignment', () { test('ObjectAlignment.byName', () { expect( ObjectAlignment.fromName('unspecified'), ObjectAlignment.unspecified, ); expect(ObjectAlignment.fromName('topleft'), ObjectAlignment.topLeft); expect(ObjectAlignment.fromName('top'), ObjectAlignment.top); expect(ObjectAlignment.fromName('topright'), ObjectAlignment.topRight); expect(ObjectAlignment.fromName('left'), ObjectAlignment.left); expect(ObjectAlignment.fromName('center'), ObjectAlignment.center); expect(ObjectAlignment.fromName('right'), ObjectAlignment.right); expect( ObjectAlignment.fromName('bottomleft'), ObjectAlignment.bottomLeft, ); expect(ObjectAlignment.fromName('bottom'), ObjectAlignment.bottom); expect( ObjectAlignment.fromName('bottomright'), ObjectAlignment.bottomRight, ); }); }); }
tiled.dart/packages/tiled/test/object_alignment_test.dart/0
{'file_path': 'tiled.dart/packages/tiled/test/object_alignment_test.dart', 'repo_id': 'tiled.dart', 'token_count': 383}
library time; export './src/extensions.dart';
time.dart/lib/time.dart/0
{'file_path': 'time.dart/lib/time.dart', 'repo_id': 'time.dart', 'token_count': 17}
import 'package:flutter/material.dart'; import 'package:travel_ui/app/presentation/ui/screens/main_screen.dart'; import 'package:travel_ui/src/res/images.dart'; import 'package:travel_ui/src/utils/margins/y_margin.dart'; import 'package:travel_ui/src/values/colors.dart'; class OnboardingScreen extends StatelessWidget { const OnboardingScreen({ super.key, }); @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 28.0, ), child: Column( children: [ const YMargin(80), Image.asset( kImgOnboardingFeatured, ), const YMargin(32), Expanded( child: Container( width: double.infinity, padding: const EdgeInsets.only( left: 22.0, right: 22.0, top: 28.0, bottom: 32.0, ), decoration: BoxDecoration( color: kSecondaryColor, borderRadius: BorderRadius.circular(40), ), child: Column( children: [ Expanded( child: Column( children: const [ YMargin(32), Text( 'Easily Travel From Your Pocket', style: TextStyle( fontSize: 24, fontWeight: FontWeight.w600, ), textAlign: TextAlign.center, ), YMargin(16), Text( 'Easily plan, manage and order your trip, and journey with Safari', textAlign: TextAlign.center, style: TextStyle( fontSize: 14, fontWeight: FontWeight.w400, ), ), ], ), ), SizedBox( width: double.infinity, child: ElevatedButton( onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (_) => const MainScreen(), ), ); }, style: ElevatedButton.styleFrom( padding: const EdgeInsets.symmetric( vertical: 15, ), elevation: 0, backgroundColor: kPrimaryColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), ), child: const Text( 'Get Started', style: TextStyle( fontSize: 20, fontWeight: FontWeight.w600, ), ), ), ) ], ), ), ), ], ), ), ), ); } }
travel_ui/lib/app/presentation/ui/screens/onboarding_screen.dart/0
{'file_path': 'travel_ui/lib/app/presentation/ui/screens/onboarding_screen.dart', 'repo_id': 'travel_ui', 'token_count': 2566}
void main() { // testWidgets('Counter increments smoke test', (WidgetTester tester) async { // // Build our app and trigger a frame. // await tester.pumpWidget(const App()); // // 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); // }); }
travel_ui/test/widget_test.dart/0
{'file_path': 'travel_ui/test/widget_test.dart', 'repo_id': 'travel_ui', 'token_count': 207}
import 'package:flame/components.dart'; import 'package:trex/game/collision/collision_box.dart'; class TRexConfig { final double gravity = 1; final double initialJumpVelocity = -15.0; final double introDuration = 1500.0; final double maxJumpHeight = 30.0; final double minJumpHeight = 30.0; final double speedDropCoefficient = 3.0; final double startXPos = 50.0; final double height = 90.0; final double width = 88.0; final double heightDuck = 50.0; final double widthDuck = 118.0; } final tRexCollisionBoxesDucking = <CollisionBox>[ CollisionBox( position: Vector2(1.0, 18.0), size: Vector2(110.0, 50.0), ), ]; final tRexCollisionBoxesRunning = <CollisionBox>[ CollisionBox( position: Vector2(22.0, 0.0), size: Vector2(34.0, 32.0), ), CollisionBox( position: Vector2(1.0, 18.0), size: Vector2(60.0, 18.0), ), CollisionBox( position: Vector2(10.0, 35.0), size: Vector2(28.0, 16.0), ), CollisionBox( position: Vector2(1.0, 24.0), size: Vector2(58.0, 10.0), ), CollisionBox( position: Vector2(5.0, 30.0), size: Vector2(42.0, 8.0), ), CollisionBox( position: Vector2(9.0, 34.0), size: Vector2(30.0, 8.0), ) ];
trex-flame/lib/game/t_rex/config.dart/0
{'file_path': 'trex-flame/lib/game/t_rex/config.dart', 'repo_id': 'trex-flame', 'token_count': 508}
void main() {}
trex-flame/test/widget_test.dart/0
{'file_path': 'trex-flame/test/widget_test.dart', 'repo_id': 'trex-flame', 'token_count': 5}
name: Dart CI on: [push] jobs: test: runs-on: ubuntu-latest container: image: google/dart:dev steps: - uses: actions/checkout@v1 - name: Install dependencies run: pub get - name: format run: dartfmt -n --set-exit-if-changed . - name: analyzer run: dartanalyzer --fatal-warnings --fatal-infos . - name: Run tests run: pub run test - name: Collect coverage run: | pub global activate test_coverage pub global run test_coverage - uses: codecov/codecov-action@v1.0.0 with: token: ${{ secrets.CODECOV_TOKEN }} file: coverage/lcov.info
union/.github/workflows/dart.yml/0
{'file_path': 'union/.github/workflows/dart.yml', 'repo_id': 'union', 'token_count': 324}
import 'package:flutter/material.dart'; import 'package:beamer/beamer.dart'; import 'package:flutter/scheduler.dart'; void main() { runApp(BooksApp()); timeDilation = 3.0; } class Book { final String title; final String author; Book(this.title, this.author); } final List<Book> books = [ Book('Stranger in a Strange Land', 'Robert A. Heinlein'), Book('Foundation', 'Isaac Asimov'), Book('Fahrenheit 451', 'Ray Bradbury'), ]; class BooksApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp.router( title: 'Books App', routerDelegate: BeamerDelegate( notFoundRedirectNamed: '/', locationBuilder: SimpleLocationBuilder( routes: { '/': (context) => BooksListScreen( books: books, onTapped: (index) => context.beamToNamed('/books/$index'), ), '/books/:bookId': (context) { final bookId = int.parse( context.currentBeamLocation.state.pathParameters['bookId']!); return BeamPage( key: ValueKey('book-$bookId'), popToNamed: '/', child: BookDetailsScreen( book: books[bookId], ), ); }, }, ), ), routeInformationParser: BeamerParser(), ); } } class BooksListScreen extends StatelessWidget { final List<Book> books; final ValueChanged<int> onTapped; BooksListScreen({ required this.books, required this.onTapped, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView( children: [ for (var book in books) ListTile( title: Text(book.title), subtitle: Text(book.author), onTap: () => onTapped(books.indexOf(book)), ) ], ), ); } } class BookDetailsScreen extends StatelessWidget { final Book book; BookDetailsScreen({ required this.book, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(book.title, style: Theme.of(context).textTheme.headline6), Text(book.author, style: Theme.of(context).textTheme.subtitle1), ], ), ), ); } }
uxr/nav2-usability/scenario_code/lib/deeplink-pathparam/deeplink_pathparam_beamer.dart/0
{'file_path': 'uxr/nav2-usability/scenario_code/lib/deeplink-pathparam/deeplink_pathparam_beamer.dart', 'repo_id': 'uxr', 'token_count': 1175}
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:beamer/beamer.dart'; void main() { runApp(WishlistApp()); } class Wishlist { final String id; Wishlist(this.id); } class AppState extends ChangeNotifier { final List<Wishlist> wishlists = <Wishlist>[]; Wishlist? _selectedWishlist; Wishlist? get selectedWishlist => _selectedWishlist; set selectedWishlist(Wishlist? w) { _selectedWishlist = w; notifyListeners(); } void addWishlist(Wishlist wishlist) { wishlists.add(wishlist); notifyListeners(); } } class WishlistLocation extends BeamLocation { WishlistLocation(AppState appState, BeamState beamState) : _appState = appState, super(beamState) { _appState.addListener( () => update((beamState) { var selectedWishlist = _appState.selectedWishlist; if (selectedWishlist != null) { return beamState.copyWith( pathBlueprintSegments: ['wishlist', ':wishlistId'], pathParameters: {'wishlistId': selectedWishlist.id}); } return beamState .copyWith(pathBlueprintSegments: ['wishlist'], pathParameters: {}); }), ); } final AppState _appState; @override List<String> get pathBlueprints => ['/wishlist/:wishlistId']; @override List<BeamPage> buildPages(BuildContext context, BeamState beamState) => [ BeamPage( key: ValueKey('wishlist-${_appState.wishlists.length}'), child: WishlistListScreen( wishlists: _appState.wishlists, onCreate: (id) { _appState.selectedWishlist = null; _appState.addWishlist(Wishlist(id)); }, onTapped: (wishlist) => _appState.selectedWishlist = wishlist, ), ), if (state.pathParameters.containsKey('wishlistId')) BeamPage( key: ValueKey('wishlist-${state.pathParameters['wishlistId']}'), child: WishlistScreen( wishlist: _appState.wishlists.firstWhere( (wishlist) => wishlist.id == beamState.pathParameters['wishlistId'], orElse: () { final wishlist = Wishlist(state.pathParameters['wishlistId']!); _appState.wishlists.add(wishlist); return wishlist; }, ), ), ), ]; } class WishlistApp extends StatelessWidget { final AppState _appState = AppState(); @override Widget build(BuildContext context) { return MaterialApp.router( title: 'Wishlist App', routerDelegate: BeamerDelegate( transitionDelegate: NoAnimationTransitionDelegate(), locationBuilder: (beamState) => WishlistLocation(_appState, beamState), ), routeInformationParser: BeamerParser(), ); } } class WishlistListScreen extends StatelessWidget { final List<Wishlist> wishlists; final ValueChanged<Wishlist> onTapped; final ValueChanged<String> onCreate; WishlistListScreen({ required this.wishlists, required this.onTapped, required this.onCreate, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView( children: [ Padding( padding: const EdgeInsets.all(8.0), child: Text('Navigate to /wishlist/<ID> in the URL bar to dynamically ' 'create a new wishlist.'), ), Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () { var randomInt = Random().nextInt(10000); onCreate('$randomInt'); }, child: Text('Create a new Wishlist'), ), ), for (var i = 0; i < wishlists.length; i++) ListTile( title: Text('Wishlist ${i + 1}'), subtitle: Text(wishlists[i].id), onTap: () => onTapped(wishlists[i]), ) ], ), ); } } class WishlistScreen extends StatelessWidget { final Wishlist wishlist; WishlistScreen({ required this.wishlist, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('ID: ${wishlist.id}', style: Theme.of(context).textTheme.headline6), ], ), ), ); } }
uxr/nav2-usability/scenario_code/lib/dynamic-linking/dynamic_linking_beamer.dart/0
{'file_path': 'uxr/nav2-usability/scenario_code/lib/dynamic-linking/dynamic_linking_beamer.dart', 'repo_id': 'uxr', 'token_count': 2177}
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // Auth example // Done using AutoRoute import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'sign_in_routing_auto_route.gr.dart'; void main() { runApp(BooksApp()); } class Credentials { final String username; final String password; Credentials(this.username, this.password); } abstract class Authentication { Future<bool> isSignedIn(); Future<void> signOut(); Future<bool> signIn(String username, String password); } class MockAuthentication implements Authentication { bool _signedIn = false; @override Future<bool> isSignedIn() async { return _signedIn; } @override Future<void> signOut() async { _signedIn = false; } @override Future<bool> signIn(String username, String password) async { return _signedIn = true; } } class AppState extends ChangeNotifier { final Authentication auth; bool _isSignedIn = false; AppState(this.auth); Future<bool> signIn(String username, String password) async { var success = await auth.signIn(username, password); _isSignedIn = success; notifyListeners(); return success; } Future<void> signOut() async { await auth.signOut(); _isSignedIn = false; notifyListeners(); } bool get isSignedIn => _isSignedIn; } // Declare routing setup @MaterialAutoRouter( replaceInRouteName: 'Screen,Route', routes: <AutoRoute>[ AutoRoute( path: "/", page: AppStackScreen, children: [ AutoRoute(path: "", page: HomeScreen), AutoRoute(path: "books", page: BooksListScreen), ], ), AutoRoute(path: "/signIn", page: SignInScreen), RedirectRoute(path: "*", redirectTo: "/") ], ) class $AppRouter {} final AppState appState = AppState(MockAuthentication()); class BooksApp extends StatefulWidget { @override State<StatefulWidget> createState() => _BooksAppState(); } class _BooksAppState extends State<BooksApp> { final _appRouter = AppRouter(); @override void initState() { super.initState(); appState.addListener(() => setState(() {})); } @override Widget build(BuildContext context) { return MaterialApp.router( routerDelegate: AutoRouterDelegate.declarative( _appRouter, routes: (_) => [ if (appState.isSignedIn) AppStackRoute() else SignInRoute( onSignedIn: _handleSignedIn, ), ], ), routeInformationParser: _appRouter.defaultRouteParser(includePrefixMatches: true)); } Future _handleSignedIn(Credentials credentials) async { await appState.signIn(credentials.username, credentials.password); } } // can be replaced with the shipped in widget // EmptyRouterWidget class AppStackScreen extends StatelessWidget { @override Widget build(BuildContext context) { return AutoRouter(); } } class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Center( child: Column( children: [ ElevatedButton( onPressed: () => context.pushRoute(const BooksListRoute()), child: Text('View my bookshelf'), ), ElevatedButton( onPressed: () => appState.signOut(), child: Text('Sign out'), ), ], ), ), ); } } class SignInScreen extends StatefulWidget { final ValueChanged<Credentials> onSignedIn; SignInScreen({required this.onSignedIn}); @override _SignInScreenState createState() => _SignInScreenState(); } class _SignInScreenState extends State<SignInScreen> { String _username = ''; String _password = ''; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Center( child: Column( children: [ TextField( decoration: InputDecoration(hintText: 'username (any)'), onChanged: (s) => _username = s, ), TextField( decoration: InputDecoration(hintText: 'password (any)'), obscureText: true, onChanged: (s) => _password = s, ), ElevatedButton( onPressed: () => widget.onSignedIn(Credentials(_username, _password)), child: Text('Sign in'), ), ], ), ), ); } } class BooksListScreen extends StatelessWidget { const BooksListScreen(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView( children: [ ListTile( title: Text('Stranger in a Strange Land'), subtitle: Text('Robert A. Heinlein'), ), ListTile( title: Text('Foundation'), subtitle: Text('Isaac Asimov'), ), ListTile( title: Text('Fahrenheit 451'), subtitle: Text('Ray Bradbury'), ), ], ), ); } }
uxr/nav2-usability/scenario_code/lib/sign-in-routing/sign_in_routing_auto_route.dart/0
{'file_path': 'uxr/nav2-usability/scenario_code/lib/sign-in-routing/sign_in_routing_auto_route.dart', 'repo_id': 'uxr', 'token_count': 2209}
import 'dart:convert'; import 'dart:io'; import 'package:unified_analytics/unified_analytics.dart'; /// The allowed action strings for a given button const allowedButtonActions = { 'accept', 'dismiss', 'snooze', }; /// The allowed operators for a given condition item const allowedConditionOperators = { '>=', '<=', '>', '<', '==', '!=', }; /// Required keys for the button object const buttonRequiredKeys = [ 'buttonText', 'action', 'url', 'promptRemainsVisible', ]; /// Required keys for the condition object const conditionRequiredKeys = [ 'field', 'operator', 'value', ]; /// The top level keys that must exist for each json object /// in the array const requiredKeys = { 'uniqueId', 'startDate', 'endDate', 'description', 'snoozeForMinutes', 'samplingRate', 'conditions', 'buttons', 'excludeDashTools', }; /// Regex pattern to verify a string is a valid v4 UUID. final uuidRegexPattern = RegExp( r'^[0-9a-z]{8}\-[0-9a-z]{4}\-[0-9a-z]{4}\-[0-9a-z]{4}\-[0-9a-z]{12}$'); /// The valid dash tools stored in the [DashTool] enum Set<String> get validDashTools => DashTool.values.map((e) => e.label).toSet(); void checkJson(File contextualSurveyFile) { final jsonContents = jsonDecode(contextualSurveyFile.readAsStringSync()); if (jsonContents is! List) { throw ArgumentError('The json file must be a list'); } for (final surveyObject in jsonContents) { // Ensure that each list item is a json object / map if (surveyObject is! Map) { throw ArgumentError('Each item in the array must be a map'); } // Ensure that the number of keys found in each object is correct if (surveyObject.keys.length != requiredKeys.length) { throw ArgumentError( 'There should only be ${requiredKeys.length} keys per survey object\n' 'The required keys are: ${requiredKeys.join(', ')}'); } // Ensure that the keys themselves match what has been defined final surveyObjectKeySet = surveyObject.keys.toSet(); if (surveyObjectKeySet.intersection(requiredKeys).length != requiredKeys.length) { throw ArgumentError('Missing the following keys: ' '${requiredKeys.difference(surveyObjectKeySet).join(', ')}'); } final uniqueId = surveyObject['uniqueId'] as String; final startDate = DateTime.parse(surveyObject['startDate'] as String); final endDate = DateTime.parse(surveyObject['endDate'] as String); final description = surveyObject['description'] as String; final snoozeForMinutes = surveyObject['snoozeForMinutes'] as int; final samplingRate = surveyObject['samplingRate'] as double; final excludeDashToolsList = surveyObject['excludeDashTools'] as List; final conditionList = surveyObject['conditions'] as List; final buttonList = surveyObject['buttons'] as List; // Ensure all of the string values are not empty if (uniqueId.isEmpty) { throw ArgumentError('Unique ID cannot be an empty string'); } if (description.isEmpty) { throw ArgumentError('Description cannot be an empty string'); } // Ensure that the survey's ID is a valid v4 UUID. if (!uuidRegexPattern.hasMatch(uniqueId)) { throw ArgumentError('Ensure that the unique ID for the survey is ' 'valid UUID v4 format for survey: $uniqueId\n' 'Example: eca0100a-505b-4539-96d0-57235f816cef'); } // Validation on the periods if (startDate.isAfter(endDate)) { throw ArgumentError('End date is before the start date'); } // Ensure the numbers are greater than zero and valid if (snoozeForMinutes <= 0) { throw ArgumentError('Snooze minutes must be greater than 0'); } if (samplingRate <= 0 || samplingRate > 1.0) { throw ArgumentError('Sampling rate must be between 0 and 1 inclusive'); } // Validation on the array containing dash tools to exclude for (final excludeDashTool in excludeDashToolsList) { if (excludeDashTool is! String) { throw ArgumentError( 'Each dash tool in the exclude list must be a string'); } if (!validDashTools.contains(excludeDashTool)) { throw ArgumentError( 'The excluded dash tool: "$excludeDashTool" is not valid\n' 'Valid dash tools are: ${validDashTools.join(', ')}'); } } // Validation on the condition array for (final conditionObject in conditionList) { if (conditionObject is! Map) { throw ArgumentError('Each item in the condition array must ' 'be a map for survey: $uniqueId'); } if (conditionObject.keys.length != conditionRequiredKeys.length) { throw ArgumentError('Each condition object should only have ' '${conditionRequiredKeys.length} keys'); } final field = conditionObject['field'] as String; final operator = conditionObject['operator'] as String; final value = conditionObject['value'] as int; if (field.isEmpty) { throw ArgumentError('Field in survey: $uniqueId must not be empty'); } if (!allowedConditionOperators.contains(operator)) { throw ArgumentError( 'Non-valid operator found in condition for survey: $uniqueId'); } if (value < 0) { throw ArgumentError('Value for each condition must not be negative'); } } // Validation on the button array final buttonTextSet = <String>{}; for (final buttonObject in buttonList) { if (buttonObject is! Map) { throw ArgumentError('Each item in the button array must ' 'be a map for survey: $uniqueId'); } if (buttonObject.keys.length != buttonRequiredKeys.length) { throw ArgumentError('Each button object should only have ' '${buttonRequiredKeys.length} keys'); } final buttonText = buttonObject['buttonText'] as String; final action = buttonObject['action'] as String; final url = buttonObject['url'] as String?; // ignore: unused_local_variable final promptRemainsVisible = buttonObject['promptRemainsVisible'] as bool; if (buttonText.isEmpty) { throw ArgumentError( 'Cannot have empty text for a given button in survey: $uniqueId'); } if (!allowedButtonActions.contains(action)) { throw ArgumentError('The action: "$action" is not allowed'); } if (url != null && url.isEmpty) { throw ArgumentError('URL values must be a non-empty string or "null"'); } // If a given button has "dismiss" as the action, // there should be no URL defined. if (action == 'dismiss' && url != null) { throw ArgumentError('URL should be null if action for a button is ' '"dismiss" or "snooze" for survey: $uniqueId'); } // Add the button text to a set to ensure that // each button in a survey has a unique label. buttonTextSet.add(buttonText); } if (buttonTextSet.length != buttonList.length) { throw ArgumentError( 'Each button must have unique text in survey: $uniqueId'); } } }
uxr/surveys/survey-validator/lib/survey_validator.dart/0
{'file_path': 'uxr/surveys/survey-validator/lib/survey_validator.dart', 'repo_id': 'uxr', 'token_count': 2550}
import 'package:mason/mason.dart'; import 'package:universal_io/io.dart'; import 'package:very_good_cli/src/commands/create/templates/templates.dart'; import 'package:very_good_cli/src/logger_extension.dart'; /// {@template flutter_plugin_template} /// A Flutter plugin template. /// {@endtemplate} class FlutterPluginTemplate extends Template { /// {@macro flutter_pkg_template} FlutterPluginTemplate() : super( name: 'flutter_plugin', bundle: veryGoodFlutterPluginBundle, help: 'Generate a reusable Flutter plugin.', ); @override Future<void> onGenerateComplete(Logger logger, Directory outputDir) async { await installFlutterPackages(logger, outputDir, recursive: true); await applyDartFixes(logger, outputDir, recursive: true); _logSummary(logger); } void _logSummary(Logger logger) { logger ..info('\n') ..created('Created a Very Good Flutter Plugin! 🦄') ..info('\n'); } }
very_good_cli/lib/src/commands/create/templates/very_good_flutter_plugin/very_good_flutter_plugin_template.dart/0
{'file_path': 'very_good_cli/lib/src/commands/create/templates/very_good_flutter_plugin/very_good_flutter_plugin_template.dart', 'repo_id': 'very_good_cli', 'token_count': 362}
export 'command_helper.dart';
very_good_cli/test/helpers/helpers.dart/0
{'file_path': 'very_good_cli/test/helpers/helpers.dart', 'repo_id': 'very_good_cli', 'token_count': 11}
export 'cubit/counter_cubit.dart'; export 'view/counter_page.dart';
very_good_core/brick/__brick__/{{project_name.snakeCase()}}/lib/counter/counter.dart/0
{'file_path': 'very_good_core/brick/__brick__/{{project_name.snakeCase()}}/lib/counter/counter.dart', 'repo_id': 'very_good_core', 'token_count': 28}
name: 'ci' on: pull_request: push: branches: - main - 'releases/*' jobs: semantic-pull-request: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/semantic_pull_request.yml@v1 styling: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install dependencies run: npm ci - name: Lint run: npm run lint - name: Format run: npm run check_format unit-tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install dependencies run: npm ci - name: Test run: npm test e2e: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Test (100% requirement on 100% file) uses: ./ with: path: './fixtures/lcov.100.info' - name: Test (90% requirement on 95% file) uses: ./ with: path: './fixtures/lcov.95.info' min_coverage: 90 - name: Test (100% requirement on 95% file) uses: ./ with: path: './fixtures/lcov.95.info' exclude: '**/*_observer.dart' - name: Test (100% requirement on 95% file with excludes) uses: ./ with: path: './fixtures/lcov.95.info' exclude: '**/whatever.dart **/*_observer.dart **/does_not_matter.dart' spell-check: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/spell_check.yml@v1 with: includes: | **/*.md .*/**/*.md modified_files_only: false
very_good_coverage/.github/workflows/test.yml/0
{'file_path': 'very_good_coverage/.github/workflows/test.yml', 'repo_id': 'very_good_coverage', 'token_count': 756}
blank_issues_enabled: false
very_good_docs_site/.github/ISSUE_TEMPLATE/config.yml/0
{'file_path': 'very_good_docs_site/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'very_good_docs_site', 'token_count': 8}
export 'tapping_behavior.dart';
very_good_flame_game/src/very_good_flame_game/lib/game/entities/unicorn/behaviors/behaviors.dart/0
{'file_path': 'very_good_flame_game/src/very_good_flame_game/lib/game/entities/unicorn/behaviors/behaviors.dart', 'repo_id': 'very_good_flame_game', 'token_count': 11}
// ignore_for_file: cascade_invocations import 'package:audioplayers/audioplayers.dart'; import 'package:flame/extensions.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:very_good_flame_game/game/game.dart'; import 'package:very_good_flame_game/l10n/l10n.dart'; class _MockAppLocalizations extends Mock implements AppLocalizations {} class _MockAudioPlayer extends Mock implements AudioPlayer {} class _VeryGoodFlameGame extends VeryGoodFlameGame { _VeryGoodFlameGame({ required super.l10n, required super.effectPlayer, required super.textStyle, }); @override Future<void> onLoad() async {} } void main() { final l10n = _MockAppLocalizations(); _VeryGoodFlameGame createFlameGame() { return _VeryGoodFlameGame( l10n: l10n, effectPlayer: _MockAudioPlayer(), textStyle: const TextStyle(), ); } group('$CounterComponent', () { setUp(() { when(() => l10n.counterText(any())).thenAnswer( (invocation) => 'counterText: ${invocation.positionalArguments[0]}', ); }); testWithGame( 'has all components', createFlameGame, (game) async { final component = CounterComponent(position: Vector2.all(1)); await game.ensureAdd(component); expect(component.text, isNotNull); }, ); testWithGame( 'changes text count correctly', createFlameGame, (game) async { final component = CounterComponent(position: Vector2.all(1)); await game.ensureAdd(component); expect(component.text.text, equals('')); game.counter = 1; game.update(0.1); expect(component.text.text, equals('counterText: 1')); game.counter = 2; game.update(0.1); expect(component.text.text, equals('counterText: 2')); }, ); }); }
very_good_flame_game/src/very_good_flame_game/test/game/components/counter_component_test.dart/0
{'file_path': 'very_good_flame_game/src/very_good_flame_game/test/game/components/counter_component_test.dart', 'repo_id': 'very_good_flame_game', 'token_count': 775}
include: package:very_good_analysis/analysis_options.5.1.0.yaml
very_good_flutter_package/brick/__brick__/{{project_name.snakeCase()}}/analysis_options.yaml/0
{'file_path': 'very_good_flutter_package/brick/__brick__/{{project_name.snakeCase()}}/analysis_options.yaml', 'repo_id': 'very_good_flutter_package', 'token_count': 23}
include: package:very_good_analysis/analysis_options.5.1.0.yaml
very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{#android}}{{project_name.snakeCase()}}_android{{/android}}/analysis_options.yaml/0
{'file_path': 'very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{#android}}{{project_name.snakeCase()}}_android{{/android}}/analysis_options.yaml', 'repo_id': 'very_good_flutter_plugin', 'token_count': 23}
include: package:very_good_analysis/analysis_options.5.1.0.yaml
very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{#macos}}{{project_name.snakeCase()}}_macos{{/macos}}/analysis_options.yaml/0
{'file_path': 'very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{#macos}}{{project_name.snakeCase()}}_macos{{/macos}}/analysis_options.yaml', 'repo_id': 'very_good_flutter_plugin', 'token_count': 23}
include: package:very_good_analysis/analysis_options.5.1.0.yaml
very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{project_name.snakeCase()}}/example/actions/check_platform_name/analysis_options.yaml/0
{'file_path': 'very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{project_name.snakeCase()}}/example/actions/check_platform_name/analysis_options.yaml', 'repo_id': 'very_good_flutter_plugin', 'token_count': 23}
import 'package:mason/mason.dart'; void run(HookContext context) { const availablePlatforms = [ 'android', 'ios', 'macos', 'linux', 'web', 'windows', ]; final selectedPlatforms = context.vars['platforms'] as List; for (final platform in availablePlatforms) { context.vars[platform] = selectedPlatforms.contains(platform); } }
very_good_flutter_plugin/brick/hooks/pre_gen.dart/0
{'file_path': 'very_good_flutter_plugin/brick/hooks/pre_gen.dart', 'repo_id': 'very_good_flutter_plugin', 'token_count': 135}
import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:my_plugin_platform_interface/my_plugin_platform_interface.dart'; /// The MacOS implementation of [MyPluginPlatform]. class MyPluginMacOS extends MyPluginPlatform { /// The method channel used to interact with the native platform. @visibleForTesting final methodChannel = const MethodChannel('my_plugin_macos'); /// Registers this class as the default instance of [MyPluginPlatform] static void registerWith() { MyPluginPlatform.instance = MyPluginMacOS(); } @override Future<String?> getPlatformName() { return methodChannel.invokeMethod<String>('getPlatformName'); } }
very_good_flutter_plugin/src/my_plugin/my_plugin_macos/lib/my_plugin_macos.dart/0
{'file_path': 'very_good_flutter_plugin/src/my_plugin/my_plugin_macos/lib/my_plugin_macos.dart', 'repo_id': 'very_good_flutter_plugin', 'token_count': 194}
tags: golden:
very_good_infinite_list/dart_test.yaml/0
{'file_path': 'very_good_infinite_list/dart_test.yaml', 'repo_id': 'very_good_infinite_list', 'token_count': 7}
import 'package:flutter/material.dart'; import 'package:very_good_infinite_list/very_good_infinite_list.dart'; class CentralizedExamples extends StatefulWidget { const CentralizedExamples({super.key}); static Route<void> route() { return MaterialPageRoute( builder: (context) { return const CentralizedExamples(); }, ); } @override State<CentralizedExamples> createState() => _CentralizedExamplesState(); } class _CentralizedExamplesState extends State<CentralizedExamples> with SingleTickerProviderStateMixin { final tabs = const [ Tab(text: 'Loading'), Tab(text: 'Empty'), Tab(text: 'Error'), ]; late final tabBarController = TabController(length: 3, vsync: this); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Centralized Examples'), bottom: TabBar( tabs: tabs, controller: tabBarController, ), ), body: TabBarView( controller: tabBarController, children: [ _LoadingExample(), _EmptyExample(), _ErrorExample(), ], ), ); } } Widget _buildItem(BuildContext context, int index) { return ListTile( title: Text('Item $index'), ); } class _LoadingExample extends StatelessWidget { @override Widget build(BuildContext context) { return InfiniteList( itemCount: 0, isLoading: true, centerLoading: true, loadingBuilder: (_) => const SizedBox( height: 10, width: 120, child: LinearProgressIndicator(), ), onFetchData: () async {}, itemBuilder: _buildItem, ); } } class _EmptyExample extends StatelessWidget { @override Widget build(BuildContext context) { return InfiniteList( itemCount: 0, centerEmpty: true, emptyBuilder: (_) => const Text( 'No items', style: TextStyle(fontSize: 20), ), onFetchData: () async {}, itemBuilder: _buildItem, ); } } class _ErrorExample extends StatelessWidget { @override Widget build(BuildContext context) { return InfiniteList( itemCount: 0, hasError: true, centerError: true, errorBuilder: (_) => const Icon( Icons.error, size: 60, color: Colors.red, ), onFetchData: () async {}, itemBuilder: _buildItem, ); } }
very_good_infinite_list/example/lib/centralized/centralized_examples.dart/0
{'file_path': 'very_good_infinite_list/example/lib/centralized/centralized_examples.dart', 'repo_id': 'very_good_infinite_list', 'token_count': 976}
version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/packages/ranch_components" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/packages/ranch_flame" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/packages/ranch_sounds" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/packages/ranch_ui" schedule: interval: "daily"
very_good_ranch/.github/dependabot.yaml/0
{'file_path': 'very_good_ranch/.github/dependabot.yaml', 'repo_id': 'very_good_ranch', 'token_count': 254}
part of 'blessing_bloc.dart'; abstract class BlessingEvent extends Equatable { const BlessingEvent(); } class UnicornSpawned extends BlessingEvent { @override List<Object> get props => []; } class UnicornDespawned extends BlessingEvent { const UnicornDespawned(this.evolutionStage); final UnicornEvolutionStage evolutionStage; @override List<Object> get props => [evolutionStage]; } class UnicornEvolved extends BlessingEvent { const UnicornEvolved({required this.to}); final UnicornEvolutionStage to; @override List<Object> get props => [to]; }
very_good_ranch/lib/game/bloc/blessing/blessing_event.dart/0
{'file_path': 'very_good_ranch/lib/game/bloc/blessing/blessing_event.dart', 'repo_id': 'very_good_ranch', 'token_count': 168}
import 'package:flame/components.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flutter/widgets.dart'; import 'package:ranch_components/ranch_components.dart'; import 'package:very_good_ranch/config.dart'; import 'package:very_good_ranch/game/entities/entities.dart'; class PettingBehavior extends TappableBehavior<Unicorn> { late final TimerComponent _throttlingTimer; @override Future<void> onLoad() async { await add( _throttlingTimer = TimerComponent( period: Config.petThrottleDuration, autoStart: false, ), ); } @override bool onTapDown(TapDownInfo info) { if (info.handled || _throttlingTimer.timer.isRunning()) { return true; } _throttlingTimer.timer.start(); parent ..enjoyment.increaseBy(parent.evolutionStage.petEnjoymentIncrease) ..setUnicornState(UnicornState.petted); return false; } } @visibleForTesting extension PetBehaviorIncreasePerStage on UnicornEvolutionStage { double get petEnjoymentIncrease { switch (this) { case UnicornEvolutionStage.baby: return Config.petEnjoymentIncrease.baby; case UnicornEvolutionStage.child: return Config.petEnjoymentIncrease.child; case UnicornEvolutionStage.teen: return Config.petEnjoymentIncrease.teen; case UnicornEvolutionStage.adult: return Config.petEnjoymentIncrease.adult; } } }
very_good_ranch/lib/game/entities/unicorn/behaviors/petting_behavior.dart/0
{'file_path': 'very_good_ranch/lib/game/entities/unicorn/behaviors/petting_behavior.dart', 'repo_id': 'very_good_ranch', 'token_count': 529}
export 'bloc/bloc.dart'; export 'view/view.dart';
very_good_ranch/lib/game_menu/game_menu.dart/0
{'file_path': 'very_good_ranch/lib/game_menu/game_menu.dart', 'repo_id': 'very_good_ranch', 'token_count': 22}
export 'background_component.dart'; export 'background_position_delegate.dart';
very_good_ranch/packages/ranch_components/lib/src/components/background/background.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/lib/src/components/background/background.dart', 'repo_id': 'very_good_ranch', 'token_count': 23}
import 'package:dashbook/dashbook.dart'; import 'package:flame/game.dart'; import 'package:ranch_components/ranch_components.dart'; import 'package:sandbox/common/common.dart'; void addUnicornComponentStories(Dashbook dashbook) { dashbook.storiesOf('UnicornComponent').add( 'Playground', (context) { final defaultUnicorn = BabyUnicornComponent(); final unicorn = context.listProperty<UnicornComponent>( 'Unicorn evolution stage', defaultUnicorn, [ defaultUnicorn, ChildUnicornComponent(), TeenUnicornComponent(), AdultUnicornComponent(), ], ); for (final state in UnicornState.values) { context.action('play ${state.name}', (context) { unicorn.playAnimation(state); }); } final game = context.storyGame(component: unicorn); return GameWidget(game: game); }, info: 'The UnicornComponent is a component that represents a unicorn.', ); }
very_good_ranch/packages/ranch_components/sandbox/lib/stories/unicorn_component/stories.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/sandbox/lib/stories/unicorn_component/stories.dart', 'repo_id': 'very_good_ranch', 'token_count': 394}
// ignore_for_file: prefer_const_constructors import 'dart:collection'; import 'dart:math'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:ranch_flame/ranch_flame.dart'; class MockRandom extends Mock implements Random {} void main() { group('RarityList', () { late Random rnd; setUp(() { rnd = MockRandom(); }); test( 'throws assertion error when the total weight does not equal 100', () { expect( () => RarityList([Rarity(1, 10), Rarity(2, 20)]), failsAssert('The sum of the rarities weight has to equal 100%'), ); expect( () => RarityList([Rarity(1, 100), Rarity(2, 20)]), failsAssert('The sum of the rarities weight has to equal 100%'), ); }, ); test('sorts list of rarity by weight', () { final list = RarityList( [Rarity(1, 40), Rarity(2, 30), Rarity(4, 10), Rarity(3, 20)], ); expect( list.rarities, equals( UnmodifiableListView( [Rarity(1, 40), Rarity(2, 30), Rarity(3, 20), Rarity(4, 10)], ), ), ); }); test('generates a sorted probability list', () { final list = RarityList( [Rarity(1, 40), Rarity(2, 30), Rarity(4, 10), Rarity(3, 20)], ); expect( list.probabilities, equals( UnmodifiableListView([ for (var i = 0; i < 40; i++) Rarity(1, 40), for (var i = 0; i < 30; i++) Rarity(2, 30), for (var i = 0; i < 20; i++) Rarity(3, 20), for (var i = 0; i < 10; i++) Rarity(4, 10), ]), ), ); }); test('returns a random item', () { when(() => rnd.nextInt(100)).thenReturn(50); final list = RarityList<int>( [Rarity(1, 50), Rarity(2, 30), Rarity(3, 20)], ); when(() => rnd.nextInt(100)).thenReturn(0); expect(list.getRandom(rnd), 1); when(() => rnd.nextInt(100)).thenReturn(50); expect(list.getRandom(rnd), 2); when(() => rnd.nextInt(100)).thenReturn(80); expect(list.getRandom(rnd), 3); }); }); }
very_good_ranch/packages/ranch_flame/test/src/rarity_list_test.dart/0
{'file_path': 'very_good_ranch/packages/ranch_flame/test/src/rarity_list_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 1039}
import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:ranch_sounds/ranch_sounds.dart'; class MockRanchSoundPlayer extends Mock implements RanchSoundPlayer {} void main() { registerFallbackValue(RanchSound.startBackground); testWidgets('plays on mount', (tester) async { final player = MockRanchSoundPlayer(); when(() => player.play(RanchSound.startBackground)) .thenAnswer((Invocation invocation) async {}); when(() => player.stop(RanchSound.startBackground)) .thenAnswer((Invocation invocation) async {}); await tester.pumpWidget( BackgroundSoundWidget( player: player, ranchSound: RanchSound.startBackground, volume: 1, child: const SizedBox.shrink(), ), ); verify(() => player.play(RanchSound.startBackground)).called(1); }); testWidgets('change of volume sets volume', (tester) async { final player = MockRanchSoundPlayer(); when(() => player.play(RanchSound.startBackground)) .thenAnswer((Invocation invocation) async {}); when(() => player.setVolume(RanchSound.startBackground, any())) .thenAnswer((Invocation invocation) async {}); when(() => player.stop(RanchSound.startBackground)) .thenAnswer((Invocation invocation) async {}); await tester.pumpWidget( BackgroundSoundWidget( player: player, ranchSound: RanchSound.startBackground, volume: 1, child: const SizedBox.shrink(), ), ); await tester.pumpWidget( BackgroundSoundWidget( player: player, ranchSound: RanchSound.startBackground, volume: 0.5, child: const SizedBox.shrink(), ), ); verify(() => player.setVolume(RanchSound.startBackground, 0.5)).called(1); }); testWidgets( 'change of sound stops the old sound and plays new one', (tester) async { final player = MockRanchSoundPlayer(); when(() => player.play(any())) .thenAnswer((Invocation invocation) async {}); when(() => player.stop(any())) .thenAnswer((Invocation invocation) async {}); await tester.pumpWidget( BackgroundSoundWidget( player: player, ranchSound: RanchSound.startBackground, volume: 1, child: const SizedBox.shrink(), ), ); await tester.pumpWidget( BackgroundSoundWidget( player: player, ranchSound: RanchSound.gameBackground, volume: 1, child: const SizedBox.shrink(), ), ); verify(() => player.stop(RanchSound.startBackground)).called(1); verify(() => player.play(RanchSound.gameBackground)).called(1); }, ); testWidgets('stops on unmount', (tester) async { final player = MockRanchSoundPlayer(); when(() => player.play(RanchSound.startBackground)) .thenAnswer((Invocation invocation) async {}); when(() => player.stop(RanchSound.startBackground)) .thenAnswer((Invocation invocation) async {}); await tester.pumpWidget( BackgroundSoundWidget( player: player, ranchSound: RanchSound.startBackground, volume: 1, child: const SizedBox.shrink(), ), ); await tester.pumpWidget( const SizedBox.shrink(), ); verify(() => player.stop(RanchSound.startBackground)).called(1); }); }
very_good_ranch/packages/ranch_sounds/test/src/background_sound_widget_test.dart/0
{'file_path': 'very_good_ranch/packages/ranch_sounds/test/src/background_sound_widget_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 1356}
export 'theme.dart'; export 'widget.dart';
very_good_ranch/packages/ranch_ui/lib/src/widgets/unicorn_counter/unicorn_counter.dart/0
{'file_path': 'very_good_ranch/packages/ranch_ui/lib/src/widgets/unicorn_counter/unicorn_counter.dart', 'repo_id': 'very_good_ranch', 'token_count': 16}
name: sandbox description: A sandbox application for the ranch ui version: 1.0.0+1 publish_to: none environment: sdk: ">=2.18.0 <3.0.0" dependencies: dashbook: ^0.1.8 flame: 1.3.0 flutter: sdk: flutter ranch_ui: path: ../ dev_dependencies: flutter_test: sdk: flutter very_good_analysis: 3.0.2 flutter: uses-material-design: true
very_good_ranch/packages/ranch_ui/sandbox/pubspec.yaml/0
{'file_path': 'very_good_ranch/packages/ranch_ui/sandbox/pubspec.yaml', 'repo_id': 'very_good_ranch', 'token_count': 159}
// ignore_for_file: prefer_const_constructors import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:ranch_ui/ranch_ui.dart'; void main() { group('UnicornCounter', () { testWidgets('renders baby counter', (tester) async { await tester.pumpUnicornCounter( UnicornCounter( isActive: true, type: UnicornType.baby, child: SizedBox(), ), ); await expectLater( find.byType(UnicornCounter), matchesGoldenFile('golden/unicorn_counter/baby.png'), ); }); testWidgets('renders child counter', (tester) async { await tester.pumpUnicornCounter( UnicornCounter( isActive: true, type: UnicornType.child, child: SizedBox(), ), ); await expectLater( find.byType(UnicornCounter), matchesGoldenFile('golden/unicorn_counter/child.png'), ); }); testWidgets('renders teen counter', (tester) async { await tester.pumpUnicornCounter( UnicornCounter( isActive: true, type: UnicornType.teen, child: SizedBox(), ), ); await expectLater( find.byType(UnicornCounter), matchesGoldenFile('golden/unicorn_counter/teen.png'), ); }); testWidgets('renders adult counter', (tester) async { await tester.pumpUnicornCounter( UnicornCounter( isActive: true, type: UnicornType.adult, child: SizedBox(), ), ); await expectLater( find.byType(UnicornCounter), matchesGoldenFile('golden/unicorn_counter/adult.png'), ); }); testWidgets('renders inactive counter', (tester) async { await tester.pumpUnicornCounter( UnicornCounter( isActive: false, type: UnicornType.adult, child: SizedBox(), ), ); await expectLater( find.byType(UnicornCounter), matchesGoldenFile('golden/unicorn_counter/inactive.png'), ); }); testWidgets('custom theme', (tester) async { await tester.pumpUnicornCounter( const UnicornCounterTheme( data: UnicornCounterThemeData( activeColor: Color(0xFF2A020B), inactiveColor: Color(0xFF99ADFF), textStyle: TextStyle(), size: 20, ), child: UnicornCounter( isActive: true, type: UnicornType.baby, child: SizedBox(), ), ), ); await expectLater( find.byType(UnicornCounter), matchesGoldenFile('golden/unicorn_counter/theme.png'), ); await tester.pumpUnicornCounter( const UnicornCounterTheme( data: UnicornCounterThemeData( activeColor: Color(0xFF2A020B), inactiveColor: Color(0xFF99ADFF), textStyle: TextStyle(), size: 20, ), child: UnicornCounter( isActive: true, type: UnicornType.baby, child: SizedBox(), ), ), ); await expectLater( find.byType(UnicornCounter), matchesGoldenFile('golden/unicorn_counter/theme-2.png'), ); }); }); test('themes are equal', () { final theme = UnicornCounterThemeData( activeColor: Color(0xFF2A020B), inactiveColor: Color(0xFF99ADFF), textStyle: TextStyle(), size: 20, ); expect( theme, equals( UnicornCounterThemeData( activeColor: Color(0xFF2A020B), inactiveColor: Color(0xFF99ADFF), textStyle: TextStyle(), size: 20, ), ), ); }); } extension on WidgetTester { Future<void> pumpUnicornCounter(Widget widget) async { await runAsync(() async { await pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: widget, ), ), ); for (final element in find.byType(Image).evaluate()) { final widget = element.widget as Image; final image = widget.image; await precacheImage(image, element); await pumpAndSettle(); } }); } }
very_good_ranch/packages/ranch_ui/test/src/widgets/unicorn_counter/unicorn_counter_test.dart/0
{'file_path': 'very_good_ranch/packages/ranch_ui/test/src/widgets/unicorn_counter/unicorn_counter_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 2042}
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockingjay/mockingjay.dart'; import 'package:very_good_ranch/game_menu/view/instructions_dialog_page.dart'; import 'package:very_good_ranch/game_menu/view/view.dart'; import 'package:very_good_ranch/l10n/l10n.dart'; import '../../helpers/helpers.dart'; void main() { group('InstructionsDialogPage', () { testWidgets('renders correctly', (tester) async { final l10n = await AppLocalizations.delegate.load(const Locale('en')); await tester.pumpApp( const InstructionsDialogPage(), ); expect(find.text(l10n.instructions), findsOneWidget); expect(find.byType(ElevatedButton), findsOneWidget); expect(find.text(l10n.ok), findsOneWidget); // instructions content expect(find.text(l10n.instructionsText), findsOneWidget); }); group('Action button', () { testWidgets('Pressing ok goes back to settings', (tester) async { final l10n = await AppLocalizations.delegate.load(const Locale('en')); final navigator = MockNavigator(); when(() => navigator.pushReplacementNamed<void, void>(any())) .thenAnswer((_) async {}); await tester.pumpApp( const InstructionsDialogPage(), navigator: navigator, ); await Scrollable.ensureVisible(find.text(l10n.ok).evaluate().first); await tester.tap(find.text(l10n.ok)); verify( () => navigator.pushReplacementNamed<void, void>( GameMenuRoute.settings.name, ), ).called(1); }); }); }); }
very_good_ranch/test/game_menu/view/instructions_dialog_page_test.dart/0
{'file_path': 'very_good_ranch/test/game_menu/view/instructions_dialog_page_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 678}
include: package:very_good_analysis/analysis_options.4.0.0.yaml
very_good_test_runner/analysis_options.yaml/0
{'file_path': 'very_good_test_runner/analysis_options.yaml', 'repo_id': 'very_good_test_runner', 'token_count': 23}
name: docs on: pull_request: paths: - ".github/workflows/site.yaml" - "site/**" jobs: build: runs-on: ubuntu-latest defaults: run: working-directory: site steps: - name: 📚 Git Checkout uses: actions/checkout@v4 - name: ⚙️ Setup Node uses: actions/setup-node@v4 with: node-version: 16.x cache: npm cache-dependency-path: site/package-lock.json - name: 📦 Install Dependencies run: npm ci - name: ✨ Check Format run: npm run format:check - name: 🧹 Lint run: npm run lint - name: 👷 Build website run: npm run build
very_good_workflows/.github/workflows/site.yaml/0
{'file_path': 'very_good_workflows/.github/workflows/site.yaml', 'repo_id': 'very_good_workflows', 'token_count': 341}
export 'src/extensions.dart'; export 'src/margin.dart'; export 'src/scale.dart'; export 'src/scale_aware.dart'; export 'src/scale_config.dart';
vigo-interview/lib/src/utils/scaler/scaler.dart/0
{'file_path': 'vigo-interview/lib/src/utils/scaler/scaler.dart', 'repo_id': 'vigo-interview', 'token_count': 55}
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class AlertService { AlertService._(this.context); final BuildContext context; final MethodChannel _channel = MethodChannel('io.github.jogboms/alert'); bool get isIos => Theme.of(context).platform == TargetPlatform.iOS; static AlertService of(BuildContext context) => AlertService._(context); Future<void> alert() async { if (isIos) { await _channel.invokeMethod<void>('beep'); await HapticFeedback.vibrate(); } } }
voute/lib/plugins/alert_service.dart/0
{'file_path': 'voute/lib/plugins/alert_service.dart', 'repo_id': 'voute', 'token_count': 176}
import 'dart:async'; import 'package:injector/injector.dart'; import 'package:voute/models/config.dart'; abstract class Config { static Config di() => Injector.appInstance.getDependency<Config>(); Future<ConfigModel> fetch(); }
voute/lib/services/config.dart/0
{'file_path': 'voute/lib/services/config.dart', 'repo_id': 'voute', 'token_count': 81}
name: voute description: Voute. version: 0.1.0 environment: sdk: ">=2.6.0-dev <3.0.0" dependencies: flutter: sdk: flutter intl: ^0.16.0 rxdart: ^0.22.5 shared_preferences: ^0.5.4+3 flutter_spinkit: ^4.0.0 get_version: ^0.2.0+1 equatable: ^0.6.1 rebloc: ^0.3.0+1 http_middleware: git: url: https://github.com/jogboms/http_middleware.git http_logger: git: url: https://github.com/jogboms/http_logger.git provider: ^3.1.0+1 injector: ^1.0.8 built_value: ^6.3.0 built_collection: ^4.2.2 overlay_support: ^1.0.2 lumberdash: ^2.1.0 colorize_lumberdash: ^2.1.0 flutter_swiper: ^1.1.6 after_layout: ^1.0.7 dev_dependencies: flutter_test: sdk: flutter mfsao: ^0.1.3 build_runner: ^1.7.2 built_value_generator: ^6.4.0 flutter_launcher_icons: ^0.7.4 feather_icons_flutter: ^4.7.4 flutter_icons: android: "ic_launcher" ios: true image_path: "assets/ic_launcher.png" adaptive_icon_background: "assets/ic_launcher_background.png" adaptive_icon_foreground: "assets/ic_launcher_transparent.png" flutter: uses-material-design: true assets: - assets/images/ fonts: - family: OCR A Std fonts: - asset: assets/fonts/OCR A Std Regular.ttf weight: 400 - family: Montserrat fonts: - asset: assets/fonts/Montserrat-Thin.ttf weight: 100 - asset: assets/fonts/Montserrat-Light.ttf weight: 200 - asset: assets/fonts/Montserrat-Regular.ttf weight: 400 - asset: assets/fonts/Montserrat-Medium.ttf weight: 600 - asset: assets/fonts/Montserrat-SemiBold.ttf weight: 700 - asset: assets/fonts/Montserrat-Bold.ttf weight: 900
voute/pubspec.yaml/0
{'file_path': 'voute/pubspec.yaml', 'repo_id': 'voute', 'token_count': 852}
name: CI on: push jobs: build: strategy: matrix: os: [macos-latest, ubuntu-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v1 - name: Using Node 14.3.0 uses: actions/setup-node@v1 with: node-version: 14.3.0 - run: npm install - name: Run Tests uses: GabrielBB/xvfb-action@v1.2 with: run: ./cmds/ci.sh
vscode-dart-import/.github/workflows/CI.yaml/0
{'file_path': 'vscode-dart-import/.github/workflows/CI.yaml', 'repo_id': 'vscode-dart-import', 'token_count': 228}
import 'package:flutter/material.dart'; import 'ui/home/screen.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'VSCode for Mobile', theme: ThemeData.dark(), home: HomeScreen(), ); } }
vscode_ipad/lib/main.dart/0
{'file_path': 'vscode_ipad/lib/main.dart', 'repo_id': 'vscode_ipad', 'token_count': 149}
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:wallet_app_workshop/core/styles.dart'; import 'package:wallet_app_workshop/on-boarding/on_boarding_page.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light); runApp(const WalletApp()); } class WalletApp extends StatelessWidget { const WalletApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Wallet App Workshop', theme: AppThemes.darkTheme, themeMode: ThemeMode.dark, home: const OnBoardingPage(), ); } }
wallet_app_workshop/lib/main.dart/0
{'file_path': 'wallet_app_workshop/lib/main.dart', 'repo_id': 'wallet_app_workshop', 'token_count': 230}
import 'package:flutter/material.dart'; import 'package:watch_store/app/screens/home_screen.dart'; import 'package:watch_store/src/res/theme/app_theme.dart'; class WatchStore extends StatelessWidget { const WatchStore({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Watch Store', theme: appTheme(context), home: const HomeScreen(), ); } }
watch-store/lib/watch_store.dart/0
{'file_path': 'watch-store/lib/watch_store.dart', 'repo_id': 'watch-store', 'token_count': 170}
// Copyright 2020 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; /// Manages iOS Simulators. /// /// Creates a simulator or provides access to an existing simulator by /// returning [IOSSimulator] instances. /// /// Uses `xcrun simctl` command to manage the simulators. /// /// Run `xcrun simctl --help` to learn more on the details of this tool. class IosSimulatorManager { IosSimulatorManager() { if (!io.Platform.isMacOS) { throw Exception('Platform ${io.Platform.operatingSystem} is not supported' '. This class should only be used on macOS. It uses xcrun ' 'simctl command line tool to manage the iOS simulators'); } } /// Uses `xcrun simctl create` command to create an iOS Simulator. /// /// Runs `xcrun simctl list runtimes` to list the runtimes existing on your /// macOS. If runtime derived from [majorVersion] and [minorVersion] is not /// available an exception will be thrown. Use Xcode to install more versions. /// /// [device] example iPhone 11 Pro. Run `xcrun simctl list devicetypes` to /// list the device types available. If [device] is not available, an /// exception will be thrown. Use Xcode to install more versions. /// /// Use `xcrun simctl create --help` for more details. Future<IosSimulator> createSimulator( int majorVersion, int minorVersion, String device) async { final String runtime = 'iOS ${majorVersion}.${minorVersion}'; // Check if the runtime is available. final io.ProcessResult runtimeListResult = await io.Process.run('xcrun', ['simctl', 'list', 'runtimes']); if (runtimeListResult.exitCode != 0) { throw Exception('Failed to boot list runtimes(versions). Command used: ' 'xcrun simctl list runtimes'); } final String output = runtimeListResult.stdout as String; if (!output.contains(runtime)) { print(output); throw Exception('Mac does not have the requested $runtime ' 'available for simulators. Please use Xcode to install.'); } // Check if the device is available. final io.ProcessResult deviceListResult = await io.Process.run('xcrun', ['simctl', 'list', 'devicetypes']); if (deviceListResult.exitCode != 0) { throw Exception('Failed to boot list available simulator device types.' 'Command used: xcrun simctl list devicetypes'); } final String deviceListOutput = deviceListResult.stdout as String; if (!deviceListOutput.contains(device)) { print(deviceListOutput); throw Exception('Mac does not have the requested device type $device ' 'available for simulators. Please use Xcode to install.'); } // Prepate device type argument. It should look like: // com.apple.CoreSimulator.SimDeviceType.iPhone-11-Pro final String deviceTypeAsArg = 'com.apple.CoreSimulator.SimDeviceType.${device.replaceAll(' ', '-')}'; // Prepare runtime as argument using the versions. It should look like: // com.apple.CoreSimulator.SimRuntime.iOS-13-1. final String runtimeTypeAsArg = 'com.apple.CoreSimulator.SimRuntime.iOS-${majorVersion}-${minorVersion}'; final io.ProcessResult createResult = await io.Process.run('xcrun', ['simctl', 'create', device, deviceTypeAsArg, runtimeTypeAsArg]); if (createResult.exitCode != 0) { throw Exception('Failed to create requested simulator using $device ' '$deviceTypeAsArg $runtimeTypeAsArg arguments.'); } // Output will have the simulator id. final String simulatorId = createResult.stdout as String; return IosSimulator._(false, simulatorId.trim()); } /// Returns an [IosSimulator] instance to control the simulator, /// if a simulator corresponding to given [osVersion] and [phone] information /// exits. /// /// Throws if such a simulator is not available. Future<IosSimulator> getSimulator( int osMajorVersion, int osMinorVersion, String phone) async { final String simulatorVersion = '-- iOS ${osMajorVersion}.${osMinorVersion} --'; final String simulatorsList = await _listExistingSimulators(osMajorVersion, osMinorVersion); // The simulator list, have the version string followed by a list of phone // names along with their ids and their statuses. Example output 1: // -- iOS 13.5 -- // iPhone 8 (2A437C91-3B85-4D7B-BB91-32561DA07B85) (Shutdown) // iPhone 8 Plus (170207A8-7631-4CBE-940E-86A7815AEB2B) (Shutdown) // iPhone 11 (7AEC5FB9-E08A-4F7F-8CA2-1518CE3A3E0D) (Booted) // iPhone 11 Pro (D8074C8B-35A5-4DA5-9AB2-4CE738A5E5FC) (Shutdown) // iPhone 11 Pro Max (3F33AD9A-805E-43E0-A86C-8FC70464A390) (Shutdown) // -- iOS 13.6 -- // iPhone 8 (2A437C91-3B85-4D7B-BB91-32561DA07B85) (Shutdown) // iPhone 8 Plus (170207A8-7631-4CBE-940E-86A7815AEB2B) (Shutdown) // iPhone 11 (7AEC5FB9-E08A-4F7F-8CA2-1518CE3A3E0D) (Booted) // iPhone 11 Pro (D8074C8B-35A5-4DA5-9AB2-4CE738A5E5FC) (Shutdown) // -- Device Pairs -- // Example output 2 (from Mac Web Engine try bots): // == Devices == // -- iOS 13.0 -- // iPhone 8 (C142C9F5-C26E-4EB5-A2B8-915D5BD62FA5) (Shutdown) // iPhone 8 Plus (C1FE8FAA-5797-478E-8BEE-D7AD4811F08C) (Shutdown) // iPhone 11 (28A3E6C0-76E7-4EE3-9B34-B059C4BBE5CA) (Shutdown) // iPhone 11 Pro (0AD4BBA5-7BE7-415D-B9FD-D962FA8E1782) (Shutdown) // iPhone 11 Pro Max (1280DE05-B334-4E60-956F-4A62220DEFA3) (Shutdown) // iPad Pro (9.7-inch) (EDE46501-CB2B-4EA4-8B5C-13FAC6F2EC91) (Shutdown) // iPad Pro (11-inch) (E0B89C9C-6200-495C-B18B-0078CCAAC688) (Shutdown) // iPad Pro (12.9-inch) (3rd generation) (DB3EB7A8-C4D2-4F86-AFC1-D652FB0579E8) (Shutdown) // iPad Air (3rd generation) (9237DCD8-8F0E-40A6-96DF-B33C915AFE1B) (Shutdown) // == Device Pairs == final int indexOfVersionListStart = simulatorsList.indexOf(simulatorVersion); final String restOfTheOutput = simulatorsList .substring(indexOfVersionListStart + simulatorVersion.length); int indexOfNextVersion = restOfTheOutput.indexOf('--'); if (indexOfNextVersion == -1) { // Search for `== Device Pairs ==`. indexOfNextVersion = restOfTheOutput.indexOf('=='); } if (indexOfNextVersion == -1) { // Set to end of file. indexOfNextVersion = restOfTheOutput.length; } final String listOfPhones = restOfTheOutput.substring(0, indexOfNextVersion); final int indexOfPhone = listOfPhones.indexOf(phone); if (indexOfPhone == -1) { print(simulatorsList); throw Exception('Simulator of $phone is not available for iOS version ' '${osMajorVersion}.${osMinorVersion}'); } final String phoneInfo = listOfPhones.substring(indexOfPhone); final int endIndexOfPhoneId = phoneInfo.indexOf(')'); final String simulatorId = phoneInfo.substring(phoneInfo.indexOf('(') + 1, endIndexOfPhoneId); final String phoneInfoAfterId = phoneInfo.substring(endIndexOfPhoneId + 1); final String simulatorStatus = phoneInfoAfterId.substring( phoneInfoAfterId.indexOf('(') + 1, phoneInfoAfterId.indexOf(')')); return IosSimulator._(simulatorStatus == 'Booted', simulatorId); } Future<String> _listExistingSimulators( int osMajorVersion, int osMinorVersion) async { final io.ProcessResult versionResult = await io.Process.run('xcrun', ['simctl', 'list']); if (versionResult.exitCode != 0) { throw Exception('Failed to list iOS simulators.'); } final String output = versionResult.stdout as String; // If the requested iOS version simulators exists, there should be a block // starting with: `-- iOS osMajorVersion.osMinorVersion --` final bool versionCheck = output.contains('-- iOS ${osMajorVersion}.${osMinorVersion} --'); if (!versionCheck) { print(output); throw Exception( 'Requested simulator version iOS ${osMajorVersion}.${osMinorVersion} ' 'is not available.'); } return output; } } /// A class that can be used to boot/shutdown an iOS Simulator. class IosSimulator { final String id; bool _booted; bool get booted => _booted; IosSimulator._(this._booted, this.id); /// Boots the iOS Simulator using the simulator [id]. /// /// Uses `xcrun simctl boot` command to boot an iOS Simulator. /// /// If it is already booted the command will fail. Future<void> boot() async { final io.ProcessResult versionResult = await io.Process.run('xcrun', ['simctl', 'boot', '$id']); if (versionResult.exitCode != 0) { throw Exception('Failed to boot iOS simulators with id: $id.'); } this._booted = true; return; } /// Shuts down the iOS Simulator using the simulator [id]. /// /// Uses `xcrun simctl shutdown` command to boot an iOS Simulator. /// /// If the simulator is not booted, the command will fail. Future<void> shutdown() async { final io.ProcessResult versionResult = await io.Process.run('xcrun', ['simctl', 'shutdown', '$id']); if (versionResult.exitCode != 0) { throw Exception('Failed to shutdown iOS simulators with id: $id.'); } this._booted = false; return; } /// Take the screenshot of the simulator. /// /// This method takes screenshot of the entire simulator, not the /// "open application's content". Future<void> takeScreenshot( String fileName, io.Directory workingDirectory) async { final io.ProcessResult versionResult = await io.Process.run( 'xcrun', ['simctl', 'io', id, 'screenshot', fileName], workingDirectory: workingDirectory.path); if (versionResult.exitCode != 0) { throw Exception('Failed to run xcrun screenshot on iOS simulator for ' 'simulator id: $id'); } } @override String toString() { return 'iOS Simulator id: $id status: $booted'; } }
web_installers/packages/simulators/lib/simulator_manager.dart/0
{'file_path': 'web_installers/packages/simulators/lib/simulator_manager.dart', 'repo_id': 'web_installers', 'token_count': 3685}
import 'package:web/web.dart'; import 'package:web_socket_channel/html.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; /// Get am [HtmlWebSocketChannel] for the provided [socket]. WebSocketChannel getWebSocketChannel(WebSocket socket) { return HtmlWebSocketChannel(socket); }
web_socket_client/lib/src/_web_socket_channel/_web_socket_channel_html.dart/0
{'file_path': 'web_socket_client/lib/src/_web_socket_channel/_web_socket_channel_html.dart', 'repo_id': 'web_socket_client', 'token_count': 93}
import 'package:test/test.dart'; import 'package:web_socket_client/web_socket_client.dart'; void main() { group('LinearBackoff', () { test('next() returns a linearly incrementing duration.', () { const initial = Duration(seconds: 1); const increment = Duration(seconds: 2); final backoff = LinearBackoff(initial: initial, increment: increment); const expected = [ Duration(seconds: 1), Duration(seconds: 3), Duration(seconds: 5), Duration(seconds: 7), Duration(seconds: 9), Duration(seconds: 11), Duration(seconds: 13), Duration(seconds: 15), Duration(seconds: 17), Duration(seconds: 19), ]; final actual = List.generate(expected.length, (_) => backoff.next()); expect(actual, equals(expected)); }); test('next() does not exceed maximum duration.', () { const initial = Duration(seconds: 1); const increment = Duration(seconds: 2); const maximum = Duration(seconds: 5); final backoff = LinearBackoff( initial: initial, increment: increment, maximum: maximum, ); const expected = [ Duration(seconds: 1), Duration(seconds: 3), Duration(seconds: 5), Duration(seconds: 5), Duration(seconds: 5), Duration(seconds: 5), Duration(seconds: 5), Duration(seconds: 5), Duration(seconds: 5), Duration(seconds: 5), ]; final actual = List.generate(expected.length, (_) => backoff.next()); expect(actual, equals(expected)); }); test('reset() resets the backoff.', () { const initial = Duration(seconds: 1); const increment = Duration(seconds: 2); const maximum = Duration(seconds: 5); final backoff = LinearBackoff( initial: initial, increment: increment, maximum: maximum, ); expect(backoff.next(), equals(initial)); expect(backoff.next(), equals(initial + increment)); expect(backoff.reset, returnsNormally); expect(backoff.next(), equals(initial)); }); }); }
web_socket_client/test/src/backoff/linear_backoff_test.dart/0
{'file_path': 'web_socket_client/test/src/backoff/linear_backoff_test.dart', 'repo_id': 'web_socket_client', 'token_count': 841}
name: basic_hero_transition publish_to: none description: >- Shows how to create a simple or Hero animation using the Hero class directly. environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: example_utils: path: ../../example_utils flutter_test: sdk: flutter flutter: uses-material-design: true assets: - images/flippers-alpha.png
website/examples/_animation/basic_hero_animation/pubspec.yaml/0
{'file_path': 'website/examples/_animation/basic_hero_animation/pubspec.yaml', 'repo_id': 'website', 'token_count': 144}
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const appTitle = 'Opacity Demo'; return const MaterialApp( title: appTitle, home: MyHomePage(title: appTitle), ); } } // The StatefulWidget's job is to take data and create a State class. // In this case, the widget takes a title, and creates a _MyHomePageState. class MyHomePage extends StatefulWidget { const MyHomePage({ super.key, required this.title, }); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } // The State class is responsible for two things: holding some data you can // update and building the UI using that data. class _MyHomePageState extends State<MyHomePage> { // Whether the green box should be visible bool _visible = true; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( // #docregion AnimatedOpacity child: AnimatedOpacity( // If the widget is visible, animate to 0.0 (invisible). // If the widget is hidden, animate to 1.0 (fully visible). opacity: _visible ? 1.0 : 0.0, duration: const Duration(milliseconds: 500), // The green box must be a child of the AnimatedOpacity widget. // #docregion Container child: Container( width: 200, height: 200, color: Colors.green, ), // #enddocregion Container ), // #enddocregion AnimatedOpacity ), // #docregion FAB floatingActionButton: FloatingActionButton( onPressed: () { // Call setState. This tells Flutter to rebuild the // UI with the changes. setState(() { _visible = !_visible; }); }, tooltip: 'Toggle Opacity', child: const Icon(Icons.flip), ), // #enddocregion FAB ); } }
website/examples/cookbook/animation/opacity_animation/lib/main.dart/0
{'file_path': 'website/examples/cookbook/animation/opacity_animation/lib/main.dart', 'repo_id': 'website', 'token_count': 846}
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); static const appTitle = 'Drawer Demo'; @override Widget build(BuildContext context) { return const MaterialApp( title: appTitle, home: MyHomePage(title: appTitle), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _selectedIndex = 0; static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold); static const List<Widget> _widgetOptions = <Widget>[ Text( 'Index 0: Home', style: optionStyle, ), Text( 'Index 1: Business', style: optionStyle, ), Text( 'Index 2: School', style: optionStyle, ), ]; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(widget.title)), body: Center( child: _widgetOptions[_selectedIndex], ), drawer: Drawer( // Add a ListView to the drawer. This ensures the user can scroll // through the options in the drawer if there isn't enough vertical // space to fit everything. child: ListView( // Important: Remove any padding from the ListView. padding: EdgeInsets.zero, children: [ const DrawerHeader( decoration: BoxDecoration( color: Colors.blue, ), child: Text('Drawer Header'), ), ListTile( title: const Text('Home'), selected: _selectedIndex == 0, onTap: () { // Update the state of the app _onItemTapped(0); // Then close the drawer Navigator.pop(context); }, ), ListTile( title: const Text('Business'), selected: _selectedIndex == 1, onTap: () { // Update the state of the app _onItemTapped(1); // Then close the drawer Navigator.pop(context); }, ), ListTile( title: const Text('School'), selected: _selectedIndex == 2, onTap: () { // Update the state of the app _onItemTapped(2); // Then close the drawer Navigator.pop(context); }, ), ], ), ), ); } }
website/examples/cookbook/design/drawer/lib/main.dart/0
{'file_path': 'website/examples/cookbook/design/drawer/lib/main.dart', 'repo_id': 'website', 'token_count': 1344}
name: snackbars description: Sample code for snackbars cookbook recipe. environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: example_utils: path: ../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/design/snackbars/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/design/snackbars/pubspec.yaml', 'repo_id': 'website', 'token_count': 91}
import 'dart:ui' as ui; import 'package:flutter/material.dart'; @immutable class BubbleBackground extends StatelessWidget { const BubbleBackground({ super.key, required this.colors, this.child, }); final List<Color> colors; final Widget? child; @override Widget build(BuildContext context) { return CustomPaint( // #docregion ScrollableContext painter: BubblePainter( colors: colors, bubbleContext: context, scrollable: ScrollableState(), ), // #enddocregion ScrollableContext child: child, ); } } // #docregion BPWithoutPaint class BubblePainter extends CustomPainter { BubblePainter({ required ScrollableState scrollable, required BuildContext bubbleContext, required List<Color> colors, }) : _scrollable = scrollable, _bubbleContext = bubbleContext, _colors = colors; final ScrollableState _scrollable; final BuildContext _bubbleContext; final List<Color> _colors; @override bool shouldRepaint(BubblePainter oldDelegate) { return oldDelegate._scrollable != _scrollable || oldDelegate._bubbleContext != _bubbleContext || oldDelegate._colors != _colors; } // #enddocregion BPWithoutPaint @override void paint(Canvas canvas, Size size) { final scrollableBox = _scrollable.context.findRenderObject() as RenderBox; final scrollableRect = Offset.zero & scrollableBox.size; final bubbleBox = _bubbleContext.findRenderObject() as RenderBox; final origin = bubbleBox.localToGlobal(Offset.zero, ancestor: scrollableBox); final paint = Paint() ..shader = ui.Gradient.linear( scrollableRect.topCenter, scrollableRect.bottomCenter, _colors, [0.0, 1.0], TileMode.clamp, Matrix4.translationValues(-origin.dx, -origin.dy, 0.0).storage, ); canvas.drawRect(Offset.zero & size, paint); } }
website/examples/cookbook/effects/gradient_bubbles/lib/bubble_painter.dart/0
{'file_path': 'website/examples/cookbook/effects/gradient_bubbles/lib/bubble_painter.dart', 'repo_id': 'website', 'token_count': 718}
import 'package:flutter/material.dart'; void main() { runApp( const MaterialApp( home: ExampleUiLoadingAnimation(), debugShowCheckedModeBanner: false, ), ); } const _shimmerGradient = LinearGradient( colors: [ Color(0xFFEBEBF4), Color(0xFFF4F4F4), Color(0xFFEBEBF4), ], stops: [ 0.1, 0.3, 0.4, ], begin: Alignment(-1.0, -0.3), end: Alignment(1.0, 0.3), tileMode: TileMode.clamp, ); class ExampleUiLoadingAnimation extends StatefulWidget { const ExampleUiLoadingAnimation({ super.key, }); @override State<ExampleUiLoadingAnimation> createState() => _ExampleUiLoadingAnimationState(); } class _ExampleUiLoadingAnimationState extends State<ExampleUiLoadingAnimation> { bool _isLoading = true; void _toggleLoading() { setState(() { _isLoading = !_isLoading; }); } @override Widget build(BuildContext context) { return Scaffold( body: Shimmer( linearGradient: _shimmerGradient, child: ListView( physics: _isLoading ? const NeverScrollableScrollPhysics() : null, children: [ const SizedBox(height: 16), _buildTopRowList(), const SizedBox(height: 16), _buildListItem(), _buildListItem(), _buildListItem(), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _toggleLoading, child: Icon( _isLoading ? Icons.hourglass_full : Icons.hourglass_bottom, ), ), ); } Widget _buildTopRowList() { return SizedBox( height: 72, child: ListView( physics: _isLoading ? const NeverScrollableScrollPhysics() : null, scrollDirection: Axis.horizontal, shrinkWrap: true, children: [ const SizedBox(width: 16), _buildTopRowItem(), _buildTopRowItem(), _buildTopRowItem(), _buildTopRowItem(), _buildTopRowItem(), _buildTopRowItem(), ], ), ); } Widget _buildTopRowItem() { return ShimmerLoading( isLoading: _isLoading, child: const CircleListItem(), ); } Widget _buildListItem() { return ShimmerLoading( isLoading: _isLoading, child: CardListItem( isLoading: _isLoading, ), ); } } class Shimmer extends StatefulWidget { static ShimmerState? of(BuildContext context) { return context.findAncestorStateOfType<ShimmerState>(); } const Shimmer({ super.key, required this.linearGradient, this.child, }); final LinearGradient linearGradient; final Widget? child; @override ShimmerState createState() => ShimmerState(); } // #docregion ShimmerStateAnimation class ShimmerState extends State<Shimmer> with SingleTickerProviderStateMixin { late AnimationController _shimmerController; @override void initState() { super.initState(); _shimmerController = AnimationController.unbounded(vsync: this) ..repeat(min: -0.5, max: 1.5, period: const Duration(milliseconds: 1000)); } @override void dispose() { _shimmerController.dispose(); super.dispose(); } // code-excerpt-closing-bracket // #enddocregion ShimmerStateAnimation // #docregion LinearGradient LinearGradient get gradient => LinearGradient( colors: widget.linearGradient.colors, stops: widget.linearGradient.stops, begin: widget.linearGradient.begin, end: widget.linearGradient.end, transform: _SlidingGradientTransform(slidePercent: _shimmerController.value), ); // #enddocregion LinearGradient bool get isSized => (context.findRenderObject() as RenderBox).hasSize; Size get size => (context.findRenderObject() as RenderBox).size; Offset getDescendantOffset({ required RenderBox descendant, Offset offset = Offset.zero, }) { final shimmerBox = context.findRenderObject() as RenderBox; return descendant.localToGlobal(offset, ancestor: shimmerBox); } // #docregion shimmerChanges Listenable get shimmerChanges => _shimmerController; // #enddocregion shimmerChanges @override Widget build(BuildContext context) { return widget.child ?? const SizedBox(); } } // #docregion SlidingGradientTransform class _SlidingGradientTransform extends GradientTransform { const _SlidingGradientTransform({ required this.slidePercent, }); final double slidePercent; @override Matrix4? transform(Rect bounds, {TextDirection? textDirection}) { return Matrix4.translationValues(bounds.width * slidePercent, 0.0, 0.0); } } // #enddocregion SlidingGradientTransform class ShimmerLoading extends StatefulWidget { const ShimmerLoading({ super.key, required this.isLoading, required this.child, }); final bool isLoading; final Widget child; @override State<ShimmerLoading> createState() => _ShimmerLoadingState(); } // #docregion ShimmerLoadingState class _ShimmerLoadingState extends State<ShimmerLoading> { Listenable? _shimmerChanges; @override void didChangeDependencies() { super.didChangeDependencies(); if (_shimmerChanges != null) { _shimmerChanges!.removeListener(_onShimmerChange); } _shimmerChanges = Shimmer.of(context)?.shimmerChanges; if (_shimmerChanges != null) { _shimmerChanges!.addListener(_onShimmerChange); } } @override void dispose() { _shimmerChanges?.removeListener(_onShimmerChange); super.dispose(); } void _onShimmerChange() { if (widget.isLoading) { setState(() { // update the shimmer painting. }); } } // code-excerpt-closing-bracket // #enddocregion ShimmerLoadingState @override Widget build(BuildContext context) { if (!widget.isLoading) { return widget.child; } // Collect ancestor shimmer info. final shimmer = Shimmer.of(context)!; if (!shimmer.isSized) { // The ancestor Shimmer widget has not laid // itself out yet. Return an empty box. return const SizedBox(); } final shimmerSize = shimmer.size; final gradient = shimmer.gradient; final offsetWithinShimmer = shimmer.getDescendantOffset( descendant: context.findRenderObject() as RenderBox, ); return ShaderMask( blendMode: BlendMode.srcATop, shaderCallback: (bounds) { return gradient.createShader( Rect.fromLTWH( -offsetWithinShimmer.dx, -offsetWithinShimmer.dy, shimmerSize.width, shimmerSize.height, ), ); }, child: widget.child, ); } } //----------- List Items --------- class CircleListItem extends StatelessWidget { const CircleListItem({super.key}); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8), child: Container( width: 54, height: 54, decoration: const BoxDecoration( color: Colors.black, shape: BoxShape.circle, ), child: ClipOval( child: Image.network( 'https://docs.flutter.dev/cookbook' '/img-files/effects/split-check/Avatar1.jpg', fit: BoxFit.cover, ), ), ), ); } } class CardListItem extends StatelessWidget { const CardListItem({ super.key, required this.isLoading, }); final bool isLoading; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildImage(), const SizedBox(height: 16), _buildText(), ], ), ); } Widget _buildImage() { return AspectRatio( aspectRatio: 16 / 9, child: Container( width: double.infinity, decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(16), ), child: ClipRRect( borderRadius: BorderRadius.circular(16), child: Image.network( 'https://docs.flutter.dev/cookbook' '/img-files/effects/split-check/Food1.jpg', fit: BoxFit.cover, ), ), ), ); } Widget _buildText() { if (isLoading) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( width: double.infinity, height: 24, decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(16), ), ), const SizedBox(height: 16), Container( width: 250, height: 24, decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(16), ), ), ], ); } else { return const Padding( padding: EdgeInsets.symmetric(horizontal: 8), child: Text( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' 'eiusmod tempor incididunt ut labore et dolore magna aliqua.', ), ); } } }
website/examples/cookbook/effects/shimmer_loading/lib/original_example.dart/0
{'file_path': 'website/examples/cookbook/effects/shimmer_loading/lib/original_example.dart', 'repo_id': 'website', 'token_count': 3889}
// ignore_for_file: unused_element, unused_field import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import './excerpt1.dart'; // #docregion Bubbles class _TypingIndicatorState extends State<TypingIndicator> with TickerProviderStateMixin { late AnimationController _appearanceController; late Animation<double> _indicatorSpaceAnimation; late Animation<double> _smallBubbleAnimation; late Animation<double> _mediumBubbleAnimation; late Animation<double> _largeBubbleAnimation; late AnimationController _repeatingController; final List<Interval> _dotIntervals = const [ Interval(0.25, 0.8), Interval(0.35, 0.9), Interval(0.45, 1.0), ]; @override void initState() { super.initState(); _appearanceController = AnimationController( vsync: this, )..addListener(() { setState(() {}); }); _indicatorSpaceAnimation = CurvedAnimation( parent: _appearanceController, curve: const Interval(0.0, 0.4, curve: Curves.easeOut), reverseCurve: const Interval(0.0, 1.0, curve: Curves.easeOut), ).drive(Tween<double>( begin: 0.0, end: 60.0, )); _smallBubbleAnimation = CurvedAnimation( parent: _appearanceController, curve: const Interval(0.0, 0.5, curve: Curves.elasticOut), reverseCurve: const Interval(0.0, 0.3, curve: Curves.easeOut), ); _mediumBubbleAnimation = CurvedAnimation( parent: _appearanceController, curve: const Interval(0.2, 0.7, curve: Curves.elasticOut), reverseCurve: const Interval(0.2, 0.6, curve: Curves.easeOut), ); _largeBubbleAnimation = CurvedAnimation( parent: _appearanceController, curve: const Interval(0.3, 1.0, curve: Curves.elasticOut), reverseCurve: const Interval(0.5, 1.0, curve: Curves.easeOut), ); if (widget.showIndicator) { _showIndicator(); } } @override void didUpdateWidget(TypingIndicator oldWidget) { super.didUpdateWidget(oldWidget); if (widget.showIndicator != oldWidget.showIndicator) { if (widget.showIndicator) { _showIndicator(); } else { _hideIndicator(); } } } @override void dispose() { _appearanceController.dispose(); super.dispose(); } void _showIndicator() { _appearanceController ..duration = const Duration(milliseconds: 750) ..forward(); } void _hideIndicator() { _appearanceController ..duration = const Duration(milliseconds: 150) ..reverse(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _indicatorSpaceAnimation, builder: (context, child) { return SizedBox( height: _indicatorSpaceAnimation.value, child: child, ); }, child: Stack( children: [ AnimatedBubble( animation: _smallBubbleAnimation, left: 8, bottom: 8, bubble: CircleBubble( size: 8, bubbleColor: widget.bubbleColor, ), ), AnimatedBubble( animation: _mediumBubbleAnimation, left: 10, bottom: 10, bubble: CircleBubble( size: 16, bubbleColor: widget.bubbleColor, ), ), AnimatedBubble( animation: _largeBubbleAnimation, left: 12, bottom: 12, bubble: StatusBubble( dotIntervals: _dotIntervals, flashingCircleDarkColor: widget.flashingCircleDarkColor, flashingCircleBrightColor: widget.flashingCircleBrightColor, bubbleColor: widget.bubbleColor, ), ), ], ), ); } } class CircleBubble extends StatelessWidget { const CircleBubble({ super.key, required this.size, required this.bubbleColor, }); final double size; final Color bubbleColor; @override Widget build(BuildContext context) { return Container( width: size, height: size, decoration: BoxDecoration( shape: BoxShape.circle, color: bubbleColor, ), ); } } class AnimatedBubble extends StatelessWidget { const AnimatedBubble({ super.key, required this.animation, required this.left, required this.bottom, required this.bubble, }); final Animation<double> animation; final double left; final double bottom; final Widget bubble; @override Widget build(BuildContext context) { return Positioned( left: left, bottom: bottom, child: AnimatedBuilder( animation: animation, builder: (context, child) { return Transform.scale( scale: animation.value, alignment: Alignment.bottomLeft, child: child, ); }, child: bubble, ), ); } } class StatusBubble extends StatelessWidget { const StatusBubble({ super.key, required this.dotIntervals, required this.flashingCircleBrightColor, required this.flashingCircleDarkColor, required this.bubbleColor, }); final List<Interval> dotIntervals; final Color flashingCircleDarkColor; final Color flashingCircleBrightColor; final Color bubbleColor; @override Widget build(BuildContext context) { return Container( width: 85, height: 44, padding: const EdgeInsets.symmetric(horizontal: 8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(27), color: bubbleColor, ), ); } } // #enddocregion Bubbles
website/examples/cookbook/effects/typing_indicator/lib/excerpt3.dart/0
{'file_path': 'website/examples/cookbook/effects/typing_indicator/lib/excerpt3.dart', 'repo_id': 'website', 'token_count': 2391}
name: long_lists description: Example for long_lists cookbook recipe environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: example_utils: path: ../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/lists/long_lists/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/lists/long_lists/pubspec.yaml', 'repo_id': 'website', 'token_count': 91}
import 'package:flutter/material.dart'; void main() { runApp( // #docregion MaterialApp MaterialApp( title: 'Named Routes Demo', // Start the app with the "/" named route. In this case, the app starts // on the FirstScreen widget. initialRoute: '/', routes: { // When navigating to the "/" route, build the FirstScreen widget. '/': (context) => const FirstScreen(), // When navigating to the "/second" route, build the SecondScreen widget. '/second': (context) => const SecondScreen(), }, ), // #enddocregion MaterialApp ); } class FirstScreen extends StatelessWidget { const FirstScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('First Screen'), ), body: Center( child: ElevatedButton( // #docregion PushNamed // Within the `FirstScreen` widget onPressed: () { // Navigate to the second screen using a named route. Navigator.pushNamed(context, '/second'); }, // #enddocregion PushNamed child: const Text('Launch screen'), ), ), ); } } class SecondScreen extends StatelessWidget { const SecondScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Second Screen'), ), body: Center( child: ElevatedButton( // #docregion Pop // Within the SecondScreen widget onPressed: () { // Navigate back to the first screen by popping the current route // off the stack. Navigator.pop(context); }, // #enddocregion Pop child: const Text('Go back!'), ), ), ); } }
website/examples/cookbook/navigation/named_routes/lib/main.dart/0
{'file_path': 'website/examples/cookbook/navigation/named_routes/lib/main.dart', 'repo_id': 'website', 'token_count': 785}
name: passing_data description: Passing data environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: example_utils: path: ../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/navigation/passing_data/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/navigation/passing_data/pubspec.yaml', 'repo_id': 'website', 'token_count': 85}
name: delete_data description: Delete Data environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter http: ^1.1.0 dev_dependencies: example_utils: path: ../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/networking/delete_data/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/networking/delete_data/pubspec.yaml', 'repo_id': 'website', 'token_count': 95}
name: web_sockets description: Web Sockets environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter web_socket_channel: ^2.1.0 dev_dependencies: example_utils: path: ../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/networking/web_sockets/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/networking/web_sockets/pubspec.yaml', 'repo_id': 'website', 'token_count': 101}
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; // #docregion main void main() async { WidgetsFlutterBinding.ensureInitialized(); unawaited(MobileAds.instance.initialize()); runApp(MyApp()); } // #enddocregion main class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const Placeholder(); } }
website/examples/cookbook/plugins/google_mobile_ads/lib/main.dart/0
{'file_path': 'website/examples/cookbook/plugins/google_mobile_ads/lib/main.dart', 'repo_id': 'website', 'token_count': 150}
import 'package:flutter_test/flutter_test.dart'; // #docregion mockClient import 'package:http/http.dart' as http; import 'package:mocking/main.dart'; import 'package:mockito/annotations.dart'; // #enddocregion mockClient import 'package:mockito/mockito.dart'; import 'fetch_album_test.mocks.dart'; // #docregion mockClient // Generate a MockClient using the Mockito package. // Create new instances of this class in each test. @GenerateMocks([http.Client]) void main() { // #enddocregion mockClient group('fetchAlbum', () { test('returns an Album if the http call completes successfully', () async { final client = MockClient(); // Use Mockito to return a successful response when it calls the // provided http.Client. when(client .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'))) .thenAnswer((_) async => http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200)); expect(await fetchAlbum(client), isA<Album>()); }); test('throws an exception if the http call completes with an error', () { final client = MockClient(); // Use Mockito to return an unsuccessful response when it calls the // provided http.Client. when(client .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'))) .thenAnswer((_) async => http.Response('Not Found', 404)); expect(fetchAlbum(client), throwsException); }); }); // #docregion mockClient } // #enddocregion mockClient
website/examples/cookbook/testing/unit/mocking/test/fetch_album_test.dart/0
{'file_path': 'website/examples/cookbook/testing/unit/mocking/test/fetch_album_test.dart', 'repo_id': 'website', 'token_count': 559}
import 'package:json_annotation/json_annotation.dart'; part 'address.g.dart'; @JsonSerializable() class Address { String street; String city; Address(this.street, this.city); factory Address.fromJson(Map<String, dynamic> json) => _$AddressFromJson(json); Map<String, dynamic> toJson() => _$AddressToJson(this); }
website/examples/development/data-and-backend/json/lib/nested/address.dart/0
{'file_path': 'website/examples/development/data-and-backend/json/lib/nested/address.dart', 'repo_id': 'website', 'token_count': 119}
// ignore_for_file: unused_local_variable // #docregion import import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; // #enddocregion import import 'package:flutter/widgets.dart'; class IOSCompositionWidget extends StatelessWidget { const IOSCompositionWidget({super.key}); @override // #docregion iOSCompositionWidget Widget build(BuildContext context) { // This is used in the platform side to register the view. const String viewType = '<platform-view-type>'; // Pass parameters to the platform side. final Map<String, dynamic> creationParams = <String, dynamic>{}; return UiKitView( viewType: viewType, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), ); } // #enddocregion iOSCompositionWidget } class TogetherWidget extends StatelessWidget { const TogetherWidget({super.key}); @override // #docregion TogetherWidget Widget build(BuildContext context) { // This is used in the platform side to register the view. const String viewType = '<platform-view-type>'; // Pass parameters to the platform side. final Map<String, dynamic> creationParams = <String, dynamic>{}; switch (defaultTargetPlatform) { case TargetPlatform.android: // return widget on Android. case TargetPlatform.iOS: // return widget on iOS. default: throw UnsupportedError('Unsupported platform view'); } } // #enddocregion TogetherWidget }
website/examples/development/platform_integration/lib/platform_views/native_view_example_3.dart/0
{'file_path': 'website/examples/development/platform_integration/lib/platform_views/native_view_example_3.dart', 'repo_id': 'website', 'token_count': 497}
import 'package:flutter/material.dart'; // ParentWidget manages the state for TapboxB. //------------------------ ParentWidget -------------------------------- class ParentWidget extends StatefulWidget { const ParentWidget({super.key}); @override State<ParentWidget> createState() => _ParentWidgetState(); } class _ParentWidgetState extends State<ParentWidget> { bool _active = false; void _handleTapboxChanged(bool newValue) { setState(() { _active = newValue; }); } @override Widget build(BuildContext context) { return SizedBox( child: TapboxB( active: _active, onChanged: _handleTapboxChanged, ), ); } } //------------------------- TapboxB ---------------------------------- class TapboxB extends StatelessWidget { const TapboxB({ super.key, this.active = false, required this.onChanged, }); final bool active; final ValueChanged<bool> onChanged; void _handleTap() { onChanged(!active); } @override Widget build(BuildContext context) { return GestureDetector( onTap: _handleTap, child: Container( width: 200, height: 200, decoration: BoxDecoration( color: active ? Colors.lightGreen[700] : Colors.grey[600], ), child: Center( child: Text( active ? 'Active' : 'Inactive', style: const TextStyle(fontSize: 32, color: Colors.white), ), ), ), ); } }
website/examples/development/ui/interactive/lib/parent_managed.dart/0
{'file_path': 'website/examples/development/ui/interactive/lib/parent_managed.dart', 'repo_id': 'website', 'token_count': 560}
import 'package:flutter/material.dart'; void main() => runApp(const MaterialApp(home: DemoApp())); class DemoApp extends StatelessWidget { const DemoApp({super.key}); @override Widget build(BuildContext context) => const Scaffold(body: Signature()); } class Signature extends StatefulWidget { const Signature({super.key}); @override SignatureState createState() => SignatureState(); } class SignatureState extends State<Signature> { List<Offset?> _points = <Offset>[]; @override Widget build(BuildContext context) { return GestureDetector( onPanUpdate: (details) { setState(() { RenderBox? referenceBox = context.findRenderObject() as RenderBox; Offset localPosition = referenceBox.globalToLocal(details.globalPosition); _points = List.from(_points)..add(localPosition); }); }, onPanEnd: (details) => _points.add(null), child: CustomPaint( painter: SignaturePainter(_points), size: Size.infinite, ), ); } } class SignaturePainter extends CustomPainter { SignaturePainter(this.points); final List<Offset?> points; @override void paint(Canvas canvas, Size size) { var paint = Paint() ..color = Colors.black ..strokeCap = StrokeCap.round ..strokeWidth = 5; for (int i = 0; i < points.length - 1; i++) { if (points[i] != null && points[i + 1] != null) { canvas.drawLine(points[i]!, points[i + 1]!, paint); } } } @override bool shouldRepaint(SignaturePainter oldDelegate) => oldDelegate.points != points; }
website/examples/get-started/flutter-for/android_devs/lib/canvas.dart/0
{'file_path': 'website/examples/get-started/flutter-for/android_devs/lib/canvas.dart', 'repo_id': 'website', 'token_count': 606}
import 'package:flutter/cupertino.dart'; void main() { runApp( const App(), ); } class App extends StatelessWidget { const App({ super.key, }); @override Widget build(BuildContext context) { return const // #docregion Theme CupertinoApp( theme: CupertinoThemeData( brightness: Brightness.dark, ), home: HomePage(), ); // #enddocregion Theme } } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return const CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: Text( 'Cupertino', ), ), child: Center( child: // #docregion StylingTextExample Text( 'Hello, world!', style: TextStyle( fontSize: 30, fontWeight: FontWeight.bold, color: CupertinoColors.systemYellow, ), ), // #enddocregion StylingTextExample ), ); } }
website/examples/get-started/flutter-for/ios_devs/lib/cupertino_themes.dart/0
{'file_path': 'website/examples/get-started/flutter-for/ios_devs/lib/cupertino_themes.dart', 'repo_id': 'website', 'token_count': 486}
import 'dart:async'; import 'package:flutter/material.dart'; // #docregion StatefulWidget class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({ super.key, required this.title, }); final String title; @override State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); } // #enddocregion StatefulWidget // #docregion StatefulWidgetState class _MyStatefulWidgetState extends State<MyStatefulWidget> { bool showText = true; bool toggleState = true; Timer? t2; void toggleBlinkState() { setState(() { toggleState = !toggleState; }); if (!toggleState) { t2 = Timer.periodic(const Duration(milliseconds: 1000), (t) { toggleShowText(); }); } else { t2?.cancel(); } } void toggleShowText() { setState(() { showText = !showText; }); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( children: <Widget>[ if (showText) const Text( 'This execution will be done before you can blink.', ), Padding( padding: const EdgeInsets.only(top: 70), child: ElevatedButton( onPressed: toggleBlinkState, child: toggleState ? const Text('Blink') : const Text('Stop Blinking'), ), ), ], ), ), ); } } // #enddocregion StatefulWidgetState
website/examples/get-started/flutter-for/react_native_devs/lib/stateful.dart/0
{'file_path': 'website/examples/get-started/flutter-for/react_native_devs/lib/stateful.dart', 'repo_id': 'website', 'token_count': 698}
import 'package:flutter/material.dart'; class MyForm extends StatefulWidget { const MyForm({super.key}); @override State<MyForm> createState() => _MyFormState(); } class _MyFormState extends State<MyForm> { /// Create a text controller and use it to retrieve the current value /// of the TextField. final TextEditingController myController = TextEditingController(); @override void dispose() { // Clean up the controller when disposing of the widget. myController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Retrieve Text Input')), body: Padding( padding: const EdgeInsets.all(16), child: TextField(controller: myController), ), floatingActionButton: FloatingActionButton( // When the user presses the button, show an alert dialog with the // text that the user has typed into our text field. onPressed: () { showDialog( context: context, builder: (context) { return AlertDialog( // Retrieve the text that the user has entered using the // TextEditingController. content: Text(myController.text), ); }, ); }, tooltip: 'Show me the value!', child: const Icon(Icons.text_fields), ), ); } }
website/examples/get-started/flutter-for/xamarin_devs/lib/form.dart/0
{'file_path': 'website/examples/get-started/flutter-for/xamarin_devs/lib/form.dart', 'repo_id': 'website', 'token_count': 572}
import 'package:flutter/material.dart'; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { /// This widget is the root of your application. const SampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Sample App', home: SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State<SampleAppPage> createState() => _SampleAppPageState(); } class _SampleAppPageState extends State<SampleAppPage> { String? _errorText; String? _getErrorText() { return _errorText; } bool isEmail(String em) { const String emailRegexp = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|' r'(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|' r'(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'; final RegExp regExp = RegExp(emailRegexp); return regExp.hasMatch(em); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: Center( child: TextField( onSubmitted: (text) { setState(() { if (!isEmail(text)) { _errorText = 'Error: This is not an email'; } else { _errorText = null; } }); }, decoration: InputDecoration( hintText: 'This is a hint', errorText: _getErrorText(), ), ), ), ); } }
website/examples/get-started/flutter-for/xamarin_devs/lib/validation.dart/0
{'file_path': 'website/examples/get-started/flutter-for/xamarin_devs/lib/validation.dart', 'repo_id': 'website', 'token_count': 747}
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // A simple "rough and ready" example of localizing a Flutter app. // Spanish and English (locale language codes 'en' and 'es') are // supported. // The pubspec.yaml file must include flutter_localizations in its // dependencies section. For example: // // dependencies: // flutter: // sdk: flutter // flutter_localizations: // sdk: flutter // If you run this app with the device's locale set to anything but // English or Spanish, the app's locale will be English. If you // set the device's locale to Spanish, the app's locale will be // Spanish. import 'dart:async'; import 'package:flutter/foundation.dart' show SynchronousFuture; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; // #docregion Demo class DemoLocalizations { DemoLocalizations(this.locale); final Locale locale; static DemoLocalizations of(BuildContext context) { return Localizations.of<DemoLocalizations>(context, DemoLocalizations)!; } static const _localizedValues = <String, Map<String, String>>{ 'en': { 'title': 'Hello World', }, 'es': { 'title': 'Hola Mundo', }, }; static List<String> languages() => _localizedValues.keys.toList(); String get title { return _localizedValues[locale.languageCode]!['title']!; } } // #enddocregion Demo // #docregion Delegate class DemoLocalizationsDelegate extends LocalizationsDelegate<DemoLocalizations> { const DemoLocalizationsDelegate(); @override bool isSupported(Locale locale) => DemoLocalizations.languages().contains(locale.languageCode); @override Future<DemoLocalizations> load(Locale locale) { // Returning a SynchronousFuture here because an async "load" operation // isn't needed to produce an instance of DemoLocalizations. return SynchronousFuture<DemoLocalizations>(DemoLocalizations(locale)); } @override bool shouldReload(DemoLocalizationsDelegate old) => false; } // #enddocregion Delegate class DemoApp extends StatelessWidget { const DemoApp({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(DemoLocalizations.of(context).title), ), body: Center( child: Text(DemoLocalizations.of(context).title), ), ); } } class Demo extends StatelessWidget { const Demo({super.key}); @override Widget build(BuildContext context) { return MaterialApp( onGenerateTitle: (context) => DemoLocalizations.of(context).title, localizationsDelegates: const [ DemoLocalizationsDelegate(), GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], supportedLocales: const [ Locale('en', ''), Locale('es', ''), ], // Watch out: MaterialApp creates a Localizations widget // with the specified delegates. DemoLocalizations.of() // will only find the app's Localizations widget if its // context is a child of the app. home: const DemoApp(), ); } } void main() { runApp(const Demo()); }
website/examples/internationalization/minimal/lib/main.dart/0
{'file_path': 'website/examples/internationalization/minimal/lib/main.dart', 'repo_id': 'website', 'token_count': 1096}
import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart' show debugPaintSizeEnabled; void main() { debugPaintSizeEnabled = true; // Remove to suppress visual layout runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter layout demo', home: Scaffold( appBar: AppBar( title: const Text('Flutter layout demo'), ), // Change to buildColumn() for the other column example body: Center(child: buildRow()), ), ); } Widget buildRow() => // #docregion Row Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Image.asset('images/pic1.jpg'), Image.asset('images/pic2.jpg'), Image.asset('images/pic3.jpg'), ], ); // #enddocregion Row Widget buildColumn() => // #docregion Column Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Image.asset('images/pic1.jpg'), Image.asset('images/pic2.jpg'), Image.asset('images/pic3.jpg'), ], ); // #enddocregion Column }
website/examples/layout/row_column/lib/main.dart/0
{'file_path': 'website/examples/layout/row_column/lib/main.dart', 'repo_id': 'website', 'token_count': 538}
// ignore_for_file: unused_local_variable // #docregion FFI import 'dart:ffi'; import 'package:ffi/ffi.dart'; // contains .toNativeUtf16() extension method typedef MessageBoxNative = Int32 Function( IntPtr hWnd, Pointer<Utf16> lpText, Pointer<Utf16> lpCaption, Int32 uType, ); typedef MessageBoxDart = int Function( int hWnd, Pointer<Utf16> lpText, Pointer<Utf16> lpCaption, int uType, ); void exampleFfi() { final user32 = DynamicLibrary.open('user32.dll'); final messageBox = user32.lookupFunction<MessageBoxNative, MessageBoxDart>('MessageBoxW'); final result = messageBox( 0, // No owner window 'Test message'.toNativeUtf16(), // Message 'Window caption'.toNativeUtf16(), // Window title 0, // OK button only ); } // #enddocregion FFI
website/examples/resources/architectural_overview/lib/ffi.dart/0
{'file_path': 'website/examples/resources/architectural_overview/lib/ffi.dart', 'repo_id': 'website', 'token_count': 298}
import 'package:state_mgmt/src/provider.dart'; import 'package:test/test.dart'; void main() { // #docregion test test('adding item increases total cost', () { final cart = CartModel(); final startingPrice = cart.totalPrice; var i = 0; cart.addListener(() { expect(cart.totalPrice, greaterThan(startingPrice)); i++; }); cart.add(Item('Dash')); expect(i, 1); }); // #enddocregion test }
website/examples/state_mgmt/simple/test/model_test.dart/0
{'file_path': 'website/examples/state_mgmt/simple/test/model_test.dart', 'repo_id': 'website', 'token_count': 167}
// #docregion PerfOverlay import 'package:flutter/material.dart'; class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( showPerformanceOverlay: true, title: 'My Awesome App', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const MyHomePage(title: 'My Awesome App'), ); } } // #enddocregion PerfOverlay class MyHomePage extends StatelessWidget { const MyHomePage({super.key, required this.title}); final String title; @override Widget build(BuildContext context) { return Text(title); } }
website/examples/testing/code_debugging/lib/performance_overlay.dart/0
{'file_path': 'website/examples/testing/code_debugging/lib/performance_overlay.dart', 'repo_id': 'website', 'token_count': 242}