code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
import 'package:flutter/material.dart'; import 'package:textura/src/enums/textura_type.dart'; import 'package:textura/src/extensions/texture_type_extension.dart'; /// `Textura` is a widget that applies a texture as a background to its child /// widget. /// It takes a `TextureType` as a required parameter to determine which texture /// to apply. /// /// Sample Usage: /// ```dart /// Textura( /// textureType: TextureType.asphalt, /// child: YourWidget(), /// ) /// ``` /// In this usage, `YourWidget()` will be displayed with an asphalt texture /// applied as its background. class Textura extends SingleChildRenderObjectWidget { /// Constructs a `Textura` widget. /// /// The [textureType] determines which texture is applied as a background to /// the [child]. const Textura({ required this.textureType, super.key, super.child, }); /// The type of texture to be applied. final TextureType textureType; /// Creates the `RenderObject` that applies the texture. /// /// It fetches the appropriate `RenderBox` based on [textureType] /// to render the texture. @override RenderObject createRenderObject(BuildContext context) { return textureType.renderObject; } }
textura/lib/src/textura.dart/0
{'file_path': 'textura/lib/src/textura.dart', 'repo_id': 'textura', 'token_count': 357}
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class SteelTextureRenderObject extends RenderBox with RenderObjectWithChildMixin { @override void performLayout() { child?.layout(constraints, parentUsesSize: true); size = constraints.biggest; } @override void paint(PaintingContext context, Offset offset) { final canvas = context.canvas; // Base steel color final basePaint = Paint() ..color = Colors.grey[850]! ..style = PaintingStyle.fill; canvas.drawRect(offset & size, basePaint); // Adding brushed lines for texture final linePaint = Paint() ..color = Colors.white.withOpacity(0.1) ..style = PaintingStyle.stroke ..strokeWidth = 3; final random = Random(0); const lineCount = 50; for (var i = 0; i < lineCount; i++) { final y = random.nextDouble() * size.height; canvas.drawLine(Offset(0, y), Offset(size.width, y), linePaint); } // Painting the child with an offset if (child != null) { context.paintChild(child!, offset); } } }
textura/lib/src/textures/materials/steel.dart/0
{'file_path': 'textura/lib/src/textures/materials/steel.dart', 'repo_id': 'textura', 'token_count': 411}
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class WaterTextureRenderObject extends RenderBox with RenderObjectWithChildMixin { @override void performLayout() { child?.layout(constraints, parentUsesSize: true); size = constraints.biggest; } @override void paint(PaintingContext context, Offset offset) { final canvas = context.canvas; // Base water color final basePaint = Paint() ..color = Colors.blue[300]! ..style = PaintingStyle.fill; canvas.drawRect(offset & size, basePaint); // Adding wave pattern for texture final wavePaint = Paint() ..color = Colors.blue[700]! ..style = PaintingStyle.stroke; const num waveHeight = 20; final num waveWidth = size.width / 20; for (num y = 0; y < size.height; y += waveHeight * 2) { final path = Path()..moveTo(0, y.toDouble() + waveHeight); for (num x = 0; x < size.width; x += waveWidth.toInt()) { path.quadraticBezierTo( x + waveWidth / 2, y + (Random().nextBool() ? waveHeight : 0).toDouble(), (x + waveWidth).toDouble(), (y + waveHeight).toDouble(), ); } canvas.drawPath(path, wavePaint); } // Painting the child with an offset if (child != null) { context.paintChild(child!, offset); } } }
textura/lib/src/textures/miscellaneous/water.dart/0
{'file_path': 'textura/lib/src/textures/miscellaneous/water.dart', 'repo_id': 'textura', 'token_count': 545}
import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class GreekKeysTextureRenderObject extends RenderProxyBox { @override void paint(PaintingContext context, Offset offset) { super.paint(context, offset); final canvas = context.canvas; final paintLine = Paint() ..color = Colors.black ..style = PaintingStyle.stroke ..strokeWidth = 2.0; const blockSize = 20.0; for (var x = 0.0; x < size.width; x += blockSize * 2) { for (var y = 0.0; y < size.height; y += blockSize * 2) { final path = Path() ..moveTo(x, y) ..relativeLineTo(blockSize, 0) ..relativeLineTo(0, blockSize) ..relativeLineTo(blockSize, 0) ..relativeLineTo(0, blockSize) ..relativeLineTo(-blockSize, 0) ..relativeLineTo(0, -blockSize) ..relativeLineTo(-blockSize, 0) ..close(); canvas.drawPath(path, paintLine); } } } }
textura/lib/src/textures/patterns/greek_keys.dart/0
{'file_path': 'textura/lib/src/textures/patterns/greek_keys.dart', 'repo_id': 'textura', 'token_count': 422}
import 'package:example/misc_animation_keys.dart'; import 'package:example/multi_views.dart'; import 'package:example/webgl_animation_cloth.dart'; import 'package:example/webgl_animation_keyframes.dart'; import 'package:example/webgl_animation_multiple.dart'; import 'package:example/webgl_animation_skinning_additive_blending.dart'; import 'package:example/webgl_animation_skinning_blending.dart'; import 'package:example/webgl_animation_skinning_morph.dart'; import 'package:example/webgl_camera.dart'; import 'package:example/webgl_camera_array.dart'; import 'package:example/webgl_clipping.dart'; import 'package:example/webgl_clipping_advanced.dart'; import 'package:example/webgl_clipping_intersection.dart'; import 'package:example/webgl_clipping_stencil.dart'; import 'package:example/webgl_geometries.dart'; import 'package:example/webgl_geometry_colors.dart'; import 'package:example/webgl_geometry_shapes.dart'; import 'package:example/webgl_geometry_text.dart'; import 'package:example/webgl_helpers.dart'; import 'package:example/webgl_instancing_performance.dart'; import 'package:example/webgl_loader_fbx.dart'; import 'package:example/webgl_loader_gltf.dart'; import 'package:example/webgl_loader_gltf_test.dart'; import 'package:example/webgl_loader_obj.dart'; import 'package:example/webgl_loader_obj_mtl.dart'; import 'package:example/webgl_loader_texture_basis.dart'; import 'package:example/webgl_materials.dart'; import 'package:example/webgl_materials_browser.dart'; import 'package:example/webgl_morphtargets.dart'; import 'package:example/webgl_morphtargets_horse.dart'; import 'package:example/webgl_morphtargets_sphere.dart'; import 'package:example/webgl_shadow_contact.dart'; import 'package:example/webgl_shadowmap_viewer.dart'; import 'package:example/webgl_skinning_simple.dart'; import 'package:flutter/material.dart'; import 'misc_controls_arcball.dart'; import 'misc_controls_map.dart'; import 'misc_controls_orbit.dart'; import 'misc_controls_trackball.dart'; import 'webgl_loader_svg.dart'; class ExamplePage extends StatefulWidget { final String? id; const ExamplePage({Key? key, this.id}) : super(key: key); @override State<ExamplePage> createState() => _MyAppState(); } class _MyAppState extends State<ExamplePage> { @override void initState() { super.initState(); } @override Widget build(BuildContext context) { Widget page; String fileName = widget.id!; if (fileName == "webgl_camera_array") { page = WebglCameraArray(fileName: fileName); } else if (fileName == "webgl_loader_obj") { page = WebGlLoaderObj(fileName: fileName); } else if (fileName == "webgl_materials_browser") { page = WebglMaterialsBrowser(fileName: fileName); } else if (fileName == "webgl_shadow_contact") { page = WebGlShadowContact(fileName: fileName); } else if (fileName == "webgl_geometry_text") { page = WebGlGeometryText(fileName: fileName); } else if (fileName == "webgl_geometry_shapes") { page = WebGlGeometryShapes(fileName: fileName); } else if (fileName == "webgl_instancing_performance") { page = WebglInstancingPerformance(fileName: fileName); } else if (fileName == "webgl_shadowmap_viewer") { page = WebGlShadowmapViewer(fileName: fileName); } else if (fileName == "webgl_loader_gltf") { page = WebGlLoaderGtlf(fileName: fileName); } else if (fileName == "webgl_loader_gltf_test") { page = WebGlLoaderGltfTest(fileName: fileName); } else if (fileName == "webgl_loader_obj_mtl") { page = WebGlLoaderObjLtl(fileName: fileName); } else if (fileName == "webgl_animation_keyframes") { page = WebGlAnimationKeyframes(fileName: fileName); } else if (fileName == "webgl_loader_texture_basis") { page = WebGlLoaderTextureBasis(fileName: fileName); } else if (fileName == "webgl_animation_multiple") { page = WebGlAnimationMultiple(fileName: fileName); } else if (fileName == "webgl_skinning_simple") { page = WebGlSkinningSimple(fileName: fileName); } else if (fileName == "misc_animation_keys") { page = MiscAnimationKeys(fileName: fileName); } else if (fileName == "webgl_clipping_intersection") { page = WebGlClippingIntersection(fileName: fileName); } else if (fileName == "webgl_clipping_advanced") { page = WebGlClippingAdvanced(fileName: fileName); } else if (fileName == "webgl_clipping_stencil") { page = WebGlClippingStencil(fileName: fileName); } else if (fileName == "webgl_clipping") { page = WebGlClipping(fileName: fileName); } else if (fileName == "webgl_geometries") { page = WebglGeometries(fileName: fileName); } else if (fileName == "webgl_animation_cloth") { page = WebGlAnimationCloth(fileName: fileName); } else if (fileName == "webgl_materials") { page = WebGlMaterials(fileName: fileName); } else if (fileName == "webgl_animation_skinning_blending") { page = WebGlAnimationSkinningBlending(fileName: fileName); } else if (fileName == "webgl_animation_skinning_additive_blending") { page = WebglAnimationSkinningAdditiveBlending(fileName: fileName); } else if (fileName == "webgl_animation_skinning_morph") { page = WebGlAnimationSkinningMorph(fileName: fileName); } else if (fileName == "webgl_camera") { page = WebGlCamera(fileName: fileName); } else if (fileName == "webgl_geometry_colors") { page = WebGlGeometryColors(fileName: fileName); } else if (fileName == "webgl_loader_svg") { page = WebGlLoaderSvg(fileName: fileName); } else if (fileName == "webgl_helpers") { page = WebGlHelpers(fileName: fileName); } else if (fileName == "webgl_morphtargets") { page = WebGlMorphtargets(fileName: fileName); } else if (fileName == "webgl_morphtargets_sphere") { page = WebGlMorphtargetsSphere(fileName: fileName); } else if (fileName == "webgl_morphtargets_horse") { page = WebGlMorphtargetsHorse(fileName: fileName); } else if (fileName == "misc_controls_orbit") { page = MiscControlsOrbit(fileName: fileName); } else if (fileName == "misc_controls_trackball") { page = MiscControlsTrackball(fileName: fileName); } else if (fileName == "misc_controls_arcball") { page = MiscControlsArcball(fileName: fileName); } else if (fileName == "misc_controls_map") { page = MiscControlsMap(fileName: fileName); } else if (fileName == "webgl_loader_fbx") { page = WebGlLoaderFbx(fileName: fileName); } else if (fileName == "multi_views") { page = MultiViews(fileName: fileName); } else { throw ("ExamplePage fileName $fileName is not support yet "); } return page; } }
three_dart/example/lib/example_page.dart/0
{'file_path': 'three_dart/example/lib/example_page.dart', 'repo_id': 'three_dart', 'token_count': 2515}
// ignore: camel_case_types class console { static error(String message, [dynamic variables]) { _print(message, variables); } static warn(String message, [dynamic variables]) { _print(message, variables); } static info(String message, [dynamic variables]) { _print(message, variables); } static _print(String message, [dynamic variables]) { print(message + (variables == null ? "" : variables.toString())); } } final undefined = null;
three_dart/lib/extra/console.dart/0
{'file_path': 'three_dart/lib/extra/console.dart', 'repo_id': 'three_dart', 'token_count': 146}
class Layers { int mask = 1 | 0; Layers(); void set(int channel) => mask = (1 << channel | 0) >> 0; void enable(int channel) => mask = mask | (1 << channel | 0); void enableAll() => mask = 0xffffffff | 0; void toggle(int channel) => mask ^= 1 << channel | 0; void disable(int channel) => mask &= ~(1 << channel | 0); void disableAll() => mask = 0; bool test(Layers layers) => (mask & layers.mask) != 0; bool isEnabled(int channel) => (mask & (1 << channel | 0)) != 0; }
three_dart/lib/three3d/core/layers.dart/0
{'file_path': 'three_dart/lib/three3d/core/layers.dart', 'repo_id': 'three_dart', 'token_count': 169}
import 'package:three_dart/three3d/extras/core/interpolations.dart'; import 'package:three_dart/three3d/math/index.dart'; import '../core/curve.dart'; class QuadraticBezierCurve extends Curve { QuadraticBezierCurve(Vector2? v0, Vector2? v1, Vector2? v2) { type = 'QuadraticBezierCurve'; isQuadraticBezierCurve = true; this.v0 = v0 ?? Vector2(null, null); this.v1 = v1 ?? Vector2(null, null); this.v2 = v2 ?? Vector2(null, null); } QuadraticBezierCurve.fromJSON(Map<String, dynamic> json) : super.fromJSON(json) { type = 'QuadraticBezierCurve'; isQuadraticBezierCurve = true; v0.fromArray(json["v0"]); v1.fromArray(json["v1"]); v2.fromArray(json["v2"]); } @override getPoint(t, optionalTarget) { var point = optionalTarget ?? Vector2(null, null); var v0 = this.v0, v1 = this.v1, v2 = this.v2; point.set(quadraticBezier(t, v0.x, v1.x, v2.x), quadraticBezier(t, v0.y, v1.y, v2.y)); return point; } @override copy(source) { super.copy(source); v0.copy(source.v0); v1.copy(source.v1); v2.copy(source.v2); return this; } @override toJSON() { var data = super.toJSON(); data["v0"] = v0.toArray(); data["v1"] = v1.toArray(); data["v2"] = v2.toArray(); return data; } }
three_dart/lib/three3d/extras/curves/quadratic_bezier_curve.dart/0
{'file_path': 'three_dart/lib/three3d/extras/curves/quadratic_bezier_curve.dart', 'repo_id': 'three_dart', 'token_count': 595}
import 'package:flutter_gl/flutter_gl.dart'; import 'package:three_dart/three3d/core/index.dart'; import 'package:three_dart/three3d/math/index.dart'; class EdgesGeometry extends BufferGeometry { final _v0 = Vector3.init(); final _v1 = Vector3.init(); final _normal = Vector3.init(); final _triangle = Triangle.init(); EdgesGeometry(BufferGeometry geometry, thresholdAngle) : super() { type = "EdgesGeometry"; parameters = {"thresholdAngle": thresholdAngle}; thresholdAngle = (thresholdAngle != null) ? thresholdAngle : 1; var thresholdDot = Math.cos(MathUtils.deg2rad * thresholdAngle); var indexAttr = geometry.getIndex(); var positionAttr = geometry.getAttribute('position'); var indexCount = indexAttr != null ? indexAttr.count : positionAttr.count; var indexArr = [0, 0, 0]; var vertKeys = ['a', 'b', 'c']; Map hashes = {}; var edgeData = {}; List<double> vertices = []; for (var i = 0; i < indexCount; i += 3) { if (indexAttr != null) { indexArr[0] = indexAttr.getX(i)!.toInt(); indexArr[1] = indexAttr.getX(i + 1)!.toInt(); indexArr[2] = indexAttr.getX(i + 2)!.toInt(); } else { indexArr[0] = i; indexArr[1] = i + 1; indexArr[2] = i + 2; } var a = _triangle.a; var b = _triangle.b; var c = _triangle.c; a.fromBufferAttribute(positionAttr, indexArr[0]); b.fromBufferAttribute(positionAttr, indexArr[1]); c.fromBufferAttribute(positionAttr, indexArr[2]); _triangle.getNormal(_normal); // create hashes for the edge from the vertices hashes[0] = "${a.x},${a.y},${a.z}"; hashes[1] = "${b.x},${b.y},${b.z}"; hashes[2] = "${c.x},${c.y},${c.z}"; // skip degenerate triangles if (hashes[0] == hashes[1] || hashes[1] == hashes[2] || hashes[2] == hashes[0]) { continue; } // iterate over every edge for (var j = 0; j < 3; j++) { // get the first and next vertex making up the edge var jNext = (j + 1) % 3; var vecHash0 = hashes[j]; var vecHash1 = hashes[jNext]; var v0 = _triangle[vertKeys[j]]; var v1 = _triangle[vertKeys[jNext]]; var hash = "${vecHash0}_$vecHash1"; var reverseHash = "${vecHash1}_$vecHash0"; if (edgeData.containsKey(reverseHash) && edgeData[reverseHash] != null) { // if we found a sibling edge add it into the vertex array if // it meets the angle threshold and delete the edge from the map. if (_normal.dot(edgeData[reverseHash]["normal"]) <= thresholdDot) { vertices.addAll([v0.x.toDouble(), v0.y.toDouble(), v0.z.toDouble()]); vertices.addAll([v1.x.toDouble(), v1.y.toDouble(), v1.z.toDouble()]); } edgeData[reverseHash] = null; } else if (!(edgeData.containsKey(hash))) { // if we've already got an edge here then skip adding a new one edgeData[hash] = { "index0": indexArr[j], "index1": indexArr[jNext], "normal": _normal.clone(), }; } } } // iterate over all remaining, unmatched edges and add them to the vertex array for (var key in edgeData.keys) { if (edgeData[key] != null) { var ed = edgeData[key]; var index0 = ed["index0"]; var index1 = ed["index1"]; _v0.fromBufferAttribute(positionAttr, index0); _v1.fromBufferAttribute(positionAttr, index1); vertices.addAll([_v0.x.toDouble(), _v0.y.toDouble(), _v0.z.toDouble()]); vertices.addAll([_v1.x.toDouble(), _v1.y.toDouble(), _v1.z.toDouble()]); } } setAttribute('position', Float32BufferAttribute(Float32Array.from(vertices), 3, false)); } }
three_dart/lib/three3d/geometries/edges_geometry.dart/0
{'file_path': 'three_dart/lib/three3d/geometries/edges_geometry.dart', 'repo_id': 'three_dart', 'token_count': 1688}
class Cache { static bool enabled = false; static Map<String, dynamic> files = {}; static add(key, file) { if (enabled == false) return; // console.log( 'three.Cache', 'Adding key:', key ); files[key] = file; } static get(key) { if (enabled == false) return; // console.log( 'three.Cache', 'Checking key:', key ); return files[key]; } static remove(key) { files.remove(key); } static clear() { files.clear(); } }
three_dart/lib/three3d/loaders/cache.dart/0
{'file_path': 'three_dart/lib/three3d/loaders/cache.dart', 'repo_id': 'three_dart', 'token_count': 176}
import 'package:three_dart/three3d/materials/material.dart'; import 'package:three_dart/three3d/math/index.dart'; class PointsMaterial extends Material { PointsMaterial([Map<String, dynamic>? parameters]) { type = "PointsMaterial"; sizeAttenuation = true; color = Color(1, 1, 1); size = 1; fog = true; setValues(parameters); } @override PointsMaterial copy(Material source) { super.copy(source); color.copy(source.color); map = source.map; alphaMap = source.alphaMap; size = source.size; sizeAttenuation = source.sizeAttenuation; fog = source.fog; return this; } }
three_dart/lib/three3d/materials/points_material.dart/0
{'file_path': 'three_dart/lib/three3d/materials/points_material.dart', 'repo_id': 'three_dart', 'token_count': 238}
import 'package:three_dart/three3d/math/interpolant.dart'; /// /// Interpolant that evaluates to the sample value at the position preceeding /// the parameter. class DiscreteInterpolant extends Interpolant { DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) : super(parameterPositions, sampleValues, sampleSize, resultBuffer); @override interpolate(i1, t0, t, t1) { return copySampleValue_(i1 - 1); } }
three_dart/lib/three3d/math/interpolants/discrete_interpolant.dart/0
{'file_path': 'three_dart/lib/three3d/math/interpolants/discrete_interpolant.dart', 'repo_id': 'three_dart', 'token_count': 147}
String clearcoatParsFragment = """ #ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform sampler2D clearcoatNormalMap; uniform vec2 clearcoatNormalScale; #endif """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/clearcoat_pars_fragment.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/clearcoat_pars_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 118}
String ditheringFragment = """ #ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/dithering_fragment.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/dithering_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 44}
String gradientmapParsFragment = """ #ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { // dotNL will be from -1.0 to 1.0 float dotNL = dot( normal, lightDirection ); vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); #ifdef USE_GRADIENTMAP return vec3( texture2D( gradientMap, coord ).r ); #else return ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 ); #endif } """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/gradientmap_pars_fragment.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/gradientmap_pars_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 184}
String logdepthbufParsFragment = """ #if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/logdepthbuf_pars_fragment.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/logdepthbuf_pars_fragment.glsl.dart', 'repo_id': 'three_dart', 'token_count': 77}
String skinnormalVertex = """ #ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; skinMatrix += skinWeight.z * boneMatZ; skinMatrix += skinWeight.w * boneMatW; skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif #endif """;
three_dart/lib/three3d/renderers/shaders/shader_chunk/skinnormal_vertex.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_chunk/skinnormal_vertex.glsl.dart', 'repo_id': 'three_dart', 'token_count': 178}
String backgroundVert = """ varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); } """;
three_dart/lib/three3d/renderers/shaders/shader_lib/background_vert.glsl.dart/0
{'file_path': 'three_dart/lib/three3d/renderers/shaders/shader_lib/background_vert.glsl.dart', 'repo_id': 'three_dart', 'token_count': 80}
import 'package:three_dart/three3d/math/index.dart'; import 'package:three_dart/three3d/scenes/fog.dart'; class FogExp2 extends FogBase { late num density; FogExp2(color, density) { name = ''; isFogExp2 = true; if (color is int) { this.color = Color(0, 0, 0).setHex(color); } else if (color is Color) { this.color = color; } else { throw (" Fog color type: ${color.runtimeType} is not support ... "); } this.density = (density != null) ? density : 0.00025; } clone() { return FogExp2(color, density); } @override toJSON() { return { "type": 'FogExp2', "color": color.getHex(), "density": density, }; } }
three_dart/lib/three3d/scenes/fog_exp2.dart/0
{'file_path': 'three_dart/lib/three3d/scenes/fog_exp2.dart', 'repo_id': 'three_dart', 'token_count': 299}
import 'package:three_dart/three3d/constants.dart'; import 'package:three_dart/three3d/textures/texture.dart'; class VideoTexture extends Texture { VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) : super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, null) { isVideoTexture = true; this.minFilter = minFilter ?? LinearFilter; this.magFilter = magFilter ?? LinearFilter; generateMipmaps = false; } @override VideoTexture clone() { return VideoTexture(image, null, null, null, null, null, null, null, null)..copy(this); } void update() { // var video = this.image; // var hasVideoFrameCallback = 'requestVideoFrameCallback' in video; // if ( hasVideoFrameCallback == false && video.readyState >= video.HAVE_CURRENT_DATA ) { // this.needsUpdate = true; // } } // updateVideo() { // this.needsUpdate = true; // video.requestVideoFrameCallback( updateVideo ); // } // if ( 'requestVideoFrameCallback' in video ) { // video.requestVideoFrameCallback( updateVideo ); // } }
three_dart/lib/three3d/textures/video_texture.dart/0
{'file_path': 'three_dart/lib/three3d/textures/video_texture.dart', 'repo_id': 'three_dart', 'token_count': 383}
name: title-validation on: pull_request: types: [opened, reopened, synchronize] jobs: validate-pr-title: name: Validate PR title runs-on: ubuntu-latest steps: - uses: amannn/action-semantic-pull-request@v4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
tiled.dart/.github/workflows/title-validation.yml/0
{'file_path': 'tiled.dart/.github/workflows/title-validation.yml', 'repo_id': 'tiled.dart', 'token_count': 133}
part of tiled; /// Below is Tiled's documentation about how this structure is represented /// on XML files: /// /// <property> /// * name: The name of the property. /// * type: The type of the property. /// Can be string (default), int, float, bool, color, file or object /// (since 0.16, with color and file added in 0.17, and object added in 1.4). /// * value: The value of the property. /// (default string is “”, default number is 0, default boolean is “false”, /// default color is #00000000, default file is “.” (the current file’s /// parent directory)) class Property<T> { String name; PropertyType type; T value; Property({ required this.name, required this.type, required this.value, }); static Property<Object> parse(Parser parser) { final name = parser.getString('name'); final type = parser.getPropertyType('type', defaults: PropertyType.string); switch (type) { case PropertyType.object: return ObjectProperty( name: name, value: parser.getInt('value', defaults: 0), ); case PropertyType.color: return ColorProperty( name: name, value: parser.getColor('value', defaults: const Color(0x00000000)), hexValue: parser.getString('value', defaults: '#00000000'), ); case PropertyType.bool: return BoolProperty( name: name, value: parser.getBool('value', defaults: false), ); case PropertyType.float: return FloatProperty( name: name, value: parser.getDouble('value', defaults: 0), ); case PropertyType.int: return IntProperty( name: name, value: parser.getInt('value', defaults: 0), ); case PropertyType.file: return FileProperty( name: name, value: parser.getString('value', defaults: '.'), ); case PropertyType.string: final value = parser.formatSpecificParsing((json) { return json.getString('value', defaults: ''); }, (xml) { final attrString = parser.getStringOrNull('value'); if (attrString != null) { return attrString; } else { // In tmx files, multi-line text property values can be stored // inside the <property> node itself instead of in the 'value' // attribute return xml.element.innerText; } }); return StringProperty( name: name, value: value, ); } } } /// A wrapper for a Tiled property set /// /// Accessing an int value /// ```dart /// properties.get<int>('foo') == 3 /// ``` /// /// Accessing an int property: /// ```dart /// properties.getProperty<IntProperty>('foo') == /// IntProperty(name: 'foo', value: 3); /// ``` /// /// You can also use an accessor: /// ```dart /// properties['foo'] == IntProperty(name: 'foo', value: 3); /// ``` class CustomProperties extends Iterable<Property<Object>> { static const empty = CustomProperties({}); /// The properties, indexed by name final Map<String, Property<Object>> byName; const CustomProperties(this.byName); /// Get a property value by its name. /// /// [T] must be the type of the value, which depends on the property type. /// The following Tiled properties map to the follow Dart types: /// - int property -> int /// - float property -> double /// - boolean property -> bool /// - string property -> string /// - color property -> ui.Color /// - file property -> string (path) /// - object property -> int (ID) T? getValue<T>(String name) { return getProperty(name)?.value as T?; } /// Get a typed property by its name T? getProperty<T extends Property<Object>>(String name) { return byName[name] as T?; } /// Get a property by its name Property<Object>? operator [](String name) { return byName[name]; } /// Returns whether or not a property with [name] exists. bool has(String name) { return byName.containsKey(name); } @override Iterator<Property<Object>> get iterator => byName.values.iterator; } /// [value] is the ID of the object class ObjectProperty extends Property<int> { ObjectProperty({ required super.name, required super.value, }) : super(type: PropertyType.object); } /// [value] is the color class ColorProperty extends Property<Color> { final String hexValue; ColorProperty({ required super.name, required super.value, required this.hexValue, }) : super(type: PropertyType.color); } /// [value] is the string text class StringProperty extends Property<String> { StringProperty({ required super.name, required super.value, }) : super(type: PropertyType.string); } /// [value] is the path to the file class FileProperty extends Property<String> { FileProperty({ required super.name, required super.value, }) : super(type: PropertyType.file); } /// [value] is the integer number class IntProperty extends Property<int> { IntProperty({ required super.name, required super.value, }) : super(type: PropertyType.int); } /// [value] is the double-percision floating-point number class FloatProperty extends Property<double> { FloatProperty({ required super.name, required super.value, }) : super(type: PropertyType.float); } /// [value] is the boolean class BoolProperty extends Property<bool> { BoolProperty({ required super.name, required super.value, }) : super(type: PropertyType.bool); } extension PropertiesParser on Parser { CustomProperties getProperties() { final properties = formatSpecificParsing( (json) => json.getChildrenAs('properties', Property.parse), (xml) => xml .getSingleChildOrNull('properties') ?.getChildrenAs('property', Property.parse) ?? [], ); // NOTE: two properties should never have the same name, if they do // one will simply override the other final byName = properties.groupFoldBy((prop) => prop.name, (previous, element) { return element; }); return CustomProperties(byName); } }
tiled.dart/packages/tiled/lib/src/common/property.dart/0
{'file_path': 'tiled.dart/packages/tiled/lib/src/common/property.dart', 'repo_id': 'tiled.dart', 'token_count': 2224}
part of tiled; /// Below is Tiled's documentation about how this structure is represented /// on XML files: /// /// <tileset> /// /// * firstgid: The first global tile ID of this tileset (this global ID maps /// to the first tile in this tileset). /// * source: If this tileset is stored in an external TSX (Tile Set XML) file, /// this attribute refers to that file. That TSX file has the same structure /// as the <tileset> element described here. (There is the firstgid attribute /// missing and this source attribute is also not there. These two attributes /// are kept in the TMX map, since they are map specific.) /// * name: The name of this tileset. /// * tilewidth: The (maximum) width of the tiles in this tileset. /// * tileheight: The (maximum) height of the tiles in this tileset. /// * spacing: The spacing in pixels between the tiles in this tileset (applies /// to the tileset image, defaults to 0) /// * margin: The margin around the tiles in this tileset (applies to the /// tileset image, defaults to 0) /// * tilecount: The number of tiles in this tileset (since 0.13) /// * columns: The number of tile columns in the tileset. For image collection /// tilesets it is editable and is used when displaying the tileset. /// (since 0.15) /// * objectalignment: Controls the alignment for tile objects. Valid values are /// unspecified, topleft, top, topright, left, center, right, bottomleft, /// bottom and bottomright. The default value is unspecified, for /// compatibility reasons. When unspecified, tile objects use bottomleft in /// orthogonal mode and bottom in isometric mode. (since 1.4) /// /// If there are multiple <tileset> elements, they are in ascending order of /// their firstgid attribute. The first tileset always has a firstgid value of /// 1. Since Tiled 0.15, image collection tilesets do not necessarily number /// their tiles consecutively since gaps can occur when removing tiles. /// /// Image collection tilesets have no <image> tag. Instead, each tile has an /// <image> tag. /// /// Can contain at most one: <image>, <tileoffset>, <grid> (since 1.0), /// <properties>, <terraintypes>, <wangsets> (since 1.1), <transformations> /// (since 1.5) /// /// Can contain any number: <tile> class Tileset { int? firstGid; String? source; String? name; int? tileWidth; int? tileHeight; int spacing = 0; int margin = 0; int? tileCount; int? columns; ObjectAlignment objectAlignment; List<Tile> tiles = []; TiledImage? image; TileOffset? tileOffset; Grid? grid; CustomProperties properties; List<Terrain> terrains = []; List<WangSet> wangSets = []; String version = '1.0'; String? tiledVersion; String? backgroundColor; String? transparentColor; TilesetType type = TilesetType.tileset; Tileset({ this.firstGid, this.source, this.name, this.tileWidth, this.tileHeight, this.spacing = 0, this.margin = 0, this.tileCount, this.columns, this.objectAlignment = ObjectAlignment.unspecified, List<Tile> tiles = const [], this.image, this.tileOffset, this.grid, this.properties = CustomProperties.empty, this.terrains = const [], this.wangSets = const [], this.version = '1.0', this.tiledVersion, this.backgroundColor, this.transparentColor, this.type = TilesetType.tileset, }) : tiles = _generateTiles( tiles, tileCount ?? 0, columns, tileWidth, tileHeight, ) { tileCount = this.tiles.length; } factory Tileset.parse(Parser parser, {TsxProvider? tsx}) { final backgroundColor = parser.getStringOrNull('backgroundcolor'); final columns = parser.getIntOrNull('columns'); final firstGid = parser.getIntOrNull('firstgid'); final margin = parser.getInt('margin', defaults: 0); final name = parser.getStringOrNull('name'); final objectAlignment = ObjectAlignment.fromName( parser.getString('objectalignment', defaults: 'unspecified'), ); final source = parser.getStringOrNull('source'); final spacing = parser.getInt('spacing', defaults: 0); final tileCount = parser.getIntOrNull('tilecount'); final tileWidth = parser.getIntOrNull('tilewidth'); final tileHeight = parser.getIntOrNull('tileheight'); final tiledVersion = parser.getStringOrNull('tiledversion'); final transparentColor = parser.getStringOrNull('transparentcolor'); final type = parser.getTilesetType('type', defaults: TilesetType.tileset); final version = parser.getString('version', defaults: '1.0'); final image = parser.getSingleChildOrNullAs('image', TiledImage.parse); final grid = parser.getSingleChildOrNullAs('grid', Grid.parse); final tileOffset = parser.getSingleChildOrNullAs('tileoffset', TileOffset.parse); final properties = parser.getProperties(); final terrains = parser.getChildrenAs('terrains', Terrain.parse); final tiles = parser.formatSpecificParsing( (json) => json.getChildrenAs('tiles', Tile.parse), (xml) => xml.getChildrenAs('tile', Tile.parse), ); final wangSets = parser.formatSpecificParsing( (json) => json.getChildrenAs('wangsets', WangSet.parse), (xml) => xml .getSingleChildOrNull('wangsets') ?.getChildrenAs('wangset', WangSet.parse) ?? [], ); final result = Tileset( firstGid: firstGid, source: source, name: name, tileWidth: tileWidth, tileHeight: tileHeight, spacing: spacing, margin: margin, tileCount: tileCount, columns: columns, objectAlignment: objectAlignment, tiles: tiles, image: image, tileOffset: tileOffset, grid: grid, properties: properties, terrains: terrains, wangSets: wangSets, version: version, tiledVersion: tiledVersion, backgroundColor: backgroundColor, transparentColor: transparentColor, type: type, ); result._checkIfExternalTsx(source, tsx); return result; } void _checkIfExternalTsx(String? source, TsxProvider? tsx) { if (tsx != null && source != null) { final tileset = Tileset.parse( tsx.getCachedSource() ?? tsx.getSource(source), ); // Copy attributes if not null backgroundColor = tileset.backgroundColor ?? backgroundColor; columns = tileset.columns ?? columns; firstGid = tileset.firstGid ?? firstGid; grid = tileset.grid ?? grid; image = tileset.image ?? image; name = tileset.name ?? name; objectAlignment = tileset.objectAlignment; spacing = tileset.spacing; margin = tileset.margin; tileCount = tileset.tileCount ?? tileCount; tiledVersion = tileset.tiledVersion ?? tiledVersion; tileOffset = tileset.tileOffset ?? tileOffset; tileHeight = tileset.tileHeight ?? tileHeight; tileWidth = tileset.tileWidth ?? tileWidth; transparentColor = tileset.transparentColor ?? transparentColor; // Add List-Attributes properties.byName.addAll(tileset.properties.byName); terrains.addAll(tileset.terrains); tiles.addAll(tileset.tiles); wangSets.addAll(tileset.wangSets); } } Rectangle computeDrawRect(Tile tile) { final image = tile.image; if (image != null) { return Rectangle( 0, 0, image.width!.toDouble(), image.height!.toDouble(), ); } final row = tile.localId ~/ columns!; final column = tile.localId % columns!; final x = margin + (column * (tileWidth! + spacing)); final y = margin + (row * (tileHeight! + spacing)); return Rectangle( x.toDouble(), y.toDouble(), tileWidth!.toDouble(), tileHeight!.toDouble(), ); } static List<Tile> _generateTiles( List<Tile> explicitTiles, int tileCount, int? columns, int? tileWidth, int? tileHeight, ) { final tiles = <Tile>[]; for (var i = 0; i < tileCount; ++i) { Rect? imageRect; if (columns != null && columns != 0 && tileWidth != null && tileHeight != null) { final x = (i % columns) * tileWidth; final y = i ~/ columns * tileHeight; imageRect = Rect.fromLTWH( x.toDouble(), y.toDouble(), tileWidth.toDouble(), tileHeight.toDouble(), ); } tiles.add( Tile(localId: i, imageRect: imageRect), ); } for (final tile in explicitTiles) { if (tile.localId >= tiles.length) { tiles.add(tile); } else { tiles[tile.localId] = tile; } } return tiles; } }
tiled.dart/packages/tiled/lib/src/tileset/tileset.dart/0
{'file_path': 'tiled.dart/packages/tiled/lib/src/tileset/tileset.dart', 'repo_id': 'tiled.dart', 'token_count': 3223}
import 'package:flutter/material.dart'; import 'package:travel_ui/app/presentation/ui/screens/onboarding_screen.dart'; class App extends StatelessWidget { const App({ super.key, }); @override Widget build(BuildContext context) { return GestureDetector( onTap: () => FocusManager.instance.primaryFocus?.unfocus(), child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Travel UI', theme: ThemeData( primarySwatch: Colors.blue, fontFamily: 'poppins', scaffoldBackgroundColor: Colors.white, ), home: const OnboardingScreen(), ), ); } }
travel_ui/lib/app.dart/0
{'file_path': 'travel_ui/lib/app.dart', 'repo_id': 'travel_ui', 'token_count': 266}
import 'package:flutter/material.dart'; const Color kPrimaryColor = Color(0xFF1D3FFF); const Color kSecondaryColor = Color(0xFFEFF4FF); const Color kGrayColor = Color(0xFFBFBFBF);
travel_ui/lib/src/values/colors.dart/0
{'file_path': 'travel_ui/lib/src/values/colors.dart', 'repo_id': 'travel_ui', 'token_count': 66}
class HorizonConfig { late final double cloudFrequency = 0.5; late final int maxClouds = 20; late final double bgCloudSpeed = 0.2; } class HorizonDimensions { late final double width = 1200.0; late final double height = 24.0; late final double yPos = 127.0; } class CloudConfig { late final double height = 28.0; late final double maxCloudGap = 400.0; late final double minCloudGap = 100.0; late final double maxSkyLevel = 71.0; late final double minSkyLevel = 30.0; late final double width = 92.0; }
trex-flame/lib/game/horizon/config.dart/0
{'file_path': 'trex-flame/lib/game/horizon/config.dart', 'repo_id': 'trex-flame', 'token_count': 172}
class A { const A(); } class B { const B(); } class C { const C(); } class D { const D(); } class E { const E(); } class F { const F(); } class G { const G(); } class H { const H(); } class I { const I(); } // ignore: prefer_const_constructors final a = A(); // ignore: prefer_const_constructors final b = B(); // ignore: prefer_const_constructors final c = C(); // ignore: prefer_const_constructors final d = D(); // ignore: prefer_const_constructors final e = E(); // ignore: prefer_const_constructors final f = F(); // ignore: prefer_const_constructors final g = G(); // ignore: prefer_const_constructors final h = H(); // ignore: prefer_const_constructors final i = I();
union/test/common.dart/0
{'file_path': 'union/test/common.dart', 'repo_id': 'union', 'token_count': 252}
name: contextual-json-validator on: push: branches: [ main, master ] pull_request: branches: [ main, master ] workflow_dispatch: schedule: - cron: '0 0 * * 0' # weekly permissions: contents: read jobs: contextual-json-validate: runs-on: ubuntu-latest defaults: run: working-directory: surveys/survey-validator steps: - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 - uses: dart-lang/setup-dart@d6a63dab3335f427404425de0fbfed4686d93c4f - run: dart pub get - run: dart run analyze: runs-on: ubuntu-latest defaults: run: working-directory: surveys/survey-validator steps: - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 - uses: dart-lang/setup-dart@d6a63dab3335f427404425de0fbfed4686d93c4f - run: dart pub get - name: Verify formatting run: dart format --output=none --set-exit-if-changed . - name: Analyze Dart files run: dart analyze --fatal-infos
uxr/.github/workflows/contextual-json-validator.yml/0
{'file_path': 'uxr/.github/workflows/contextual-json-validator.yml', 'repo_id': 'uxr', 'token_count': 471}
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router_prototype/go_router_prototype.dart'; void main() { runApp(BooksApp()); } class Book { final String title; final String author; Book(this.title, this.author); } class BooksApp extends StatelessWidget { final List<Book> books = [ Book('Stranger in a Strange Land', 'Robert A. Heinlein'), Book('Foundation', 'Isaac Asimov'), Book('Fahrenheit 451', 'Ray Bradbury'), ]; @override Widget build(BuildContext context) { return MaterialApp.router( routeInformationParser: _router.parser, routerDelegate: _router.delegate, ); } late final _router = GoRouter( routes: [ StackedRoute( path: '/', builder: (context) => BooksListScreen( books: books, filter: RouteState.of(context).queryParameters['filter'], ), ), ], ); } class BooksListScreen extends StatelessWidget { final List<Book> books; final String? filter; BooksListScreen({required this.books, required this.filter}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView( children: [ TextField( decoration: InputDecoration( hintText: 'filter', ), onSubmitted: (value) => RouteState.of(context).goTo('/?filter=$value'), ), for (var book in books) if (filter == null || book.title.toLowerCase().contains(filter!)) ListTile( title: Text(book.title), subtitle: Text(book.author), ) ], ), ); } }
uxr/nav2-usability/scenario_code/lib/deeplink-queryparam/deeplink_queryparam_go_router_prototype.dart/0
{'file_path': 'uxr/nav2-usability/scenario_code/lib/deeplink-queryparam/deeplink_queryparam_go_router_prototype.dart', 'repo_id': 'uxr', 'token_count': 784}
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router_prototype/go_router_prototype.dart'; void main() { runApp(BooksApp()); } class BooksApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp.router( routeInformationParser: _router.parser, routerDelegate: _router.delegate, ); } late final _router = GoRouter( routes: [ ShellRoute( path: '/', defaultRoute: '/books/new', builder: (context, child) { late final int selectedIndex; final childPath = RouteState.of(context).activeChild?.path; if (childPath == null || childPath == 'books') { selectedIndex = 0; } else if (childPath == 'settings') { selectedIndex = 1; } return AppScreen( currentIndex: selectedIndex, child: child, ); }, routes: [ ShellRoute( path: 'books', defaultRoute: 'new', builder: (context, child) => BooksScreen( selectedTab: RouteState.of(context).activeChild!.path == 'new' ? 0 : 1, child: child, ), routes: [ StackedRoute( path: 'new', builder: (context) => NewBooksScreen(), ), StackedRoute( path: 'all', builder: (context) => AllBooksScreen(), ), ], ), StackedRoute( path: 'settings', builder: (context) { return SettingsScreen(); }, ), ], ), ], ); } class AppScreen extends StatelessWidget { final int currentIndex; final Widget child; const AppScreen({ Key? key, required this.currentIndex, required this.child, }) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: AnimatedSwitcher( duration: Duration(milliseconds: 400), child: child, ), bottomNavigationBar: BottomNavigationBar( currentIndex: currentIndex, onTap: (idx) { if (idx == 0) { RouteState.of(context).goTo('/books/new'); } else { RouteState.of(context).goTo('/settings'); } }, items: [ BottomNavigationBarItem( label: 'Books', icon: Icon(Icons.chrome_reader_mode_outlined), ), BottomNavigationBarItem( label: 'Settings', icon: Icon(Icons.settings), ), ], ), ); } } class BooksScreen extends StatefulWidget { final int selectedTab; final Widget child; BooksScreen({ required this.selectedTab, required this.child, Key? key, }) : super(key: key); @override _BooksScreenState createState() => _BooksScreenState(); } class _BooksScreenState extends State<BooksScreen> with SingleTickerProviderStateMixin { late final TabController _tabController; @override void initState() { _tabController = TabController(length: 2, vsync: this, initialIndex: widget.selectedTab); super.initState(); } @override void didChangeDependencies() { super.didChangeDependencies(); _tabController.animateTo(widget.selectedTab); } void dispose() { _tabController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final routeState = RouteState.of(context); return Column( children: [ TabBar( controller: _tabController, onTap: (int index) => routeState.goTo(index == 0 ? 'new' : 'all'), labelColor: Theme.of(context).primaryColor, tabs: [ Tab(icon: Icon(Icons.bathtub), text: 'New'), Tab(icon: Icon(Icons.group), text: 'All'), ], ), Expanded( child: TabBarView( controller: _tabController, children: [ NewBooksScreen(), AllBooksScreen(), ], ), ), ], ); } } class SettingsScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('Settings'), ), ); } } class AllBooksScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('All Books'), ), ); } } class NewBooksScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('New Books'), ), ); } }
uxr/nav2-usability/scenario_code/lib/nested-routing/nested_routing_go_router_prototype.dart/0
{'file_path': 'uxr/nav2-usability/scenario_code/lib/nested-routing/nested_routing_go_router_prototype.dart', 'repo_id': 'uxr', 'token_count': 2275}
// 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. /// Skipping stacks example /// Done using go_router import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; void main() { runApp(BooksApp()); } class Book { final String title; final Author author; Book(this.title, this.author); } class Author { String name; Author(this.name); } class AppState extends ChangeNotifier { final List<Book> books = [ Book('Stranger in a Strange Land', Author('Robert A. Heinlein')), Book('Foundation', Author('Isaac Asimov')), Book('Fahrenheit 451', Author('Ray Bradbury')), ]; List<Author> get authors => [...books.map((book) => book.author)]; } class BooksApp extends StatelessWidget { final AppState _appState = AppState(); @override Widget build(BuildContext context) { return MaterialApp.router( routeInformationParser: _router.routeInformationParser, routerDelegate: _router.routerDelegate, ); } late final _router = GoRouter( routes: [ // Home just redirects to the list of books GoRoute(path: '/', redirect: (_) => '/books'), // Books GoRoute( path: '/books', pageBuilder: (context, state) => MaterialPage( key: state.pageKey, child: BooksListScreen(books: _appState.books), ), routes: [ GoRoute( path: r':bookId(\d+)', pageBuilder: (context, state) { final bookId = int.parse(state.params['bookId']!); return MaterialPage( key: state.pageKey, child: BookDetailsScreen( bookId: bookId, book: _appState.books[bookId], ), ); }, ), ], ), // Authors GoRoute( path: '/authors', pageBuilder: (context, state) => MaterialPage( key: state.pageKey, child: AuthorsListScreen(authors: _appState.authors), ), routes: [ GoRoute( path: r':bookId(\d+)', pageBuilder: (context, state) { final bookId = int.parse(state.params['bookId']!); return MaterialPage( key: state.pageKey, child: AuthorDetailsScreen( author: _appState.books[bookId].author, ), ); }, ) ], ), ], errorPageBuilder: (context, state) => MaterialPage( key: state.pageKey, child: ErrorScreen(state.error), ), ); } class BooksListScreen extends StatelessWidget { final List<Book> books; BooksListScreen({required this.books}); @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.name), onTap: () => context.go('/books/${books.indexOf(book)}'), ) ], ), ); } } class AuthorsListScreen extends StatelessWidget { final List<Author> authors; AuthorsListScreen({required this.authors}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView( children: [ ElevatedButton( onPressed: () => context.go('/'), child: Text('Go to Books Screen'), ), for (var author in authors) ListTile( title: Text(author.name), onTap: () => context.go('/authors/${authors.indexOf(author)}'), ) ], ), ); } } class BookDetailsScreen extends StatelessWidget { final int bookId; final Book book; BookDetailsScreen({required this.book, required this.bookId}); @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), ElevatedButton( onPressed: () => context.go('/authors/$bookId'), child: Text(book.author.name), ), ], ), ), ); } } class AuthorDetailsScreen extends StatelessWidget { final Author author; AuthorDetailsScreen({ required this.author, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(author.name, style: Theme.of(context).textTheme.headline6), ], ), ), ); } } class ErrorScreen extends StatelessWidget { const ErrorScreen(this.error, {Key? key}) : super(key: key); final Exception? error; @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text('Page Not Found')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(error?.toString() ?? 'page not found'), TextButton( onPressed: () => context.go('/'), child: const Text('Home'), ), ], ), ), ); }
uxr/nav2-usability/scenario_code/lib/skipping-stacks/skipping_stacks_go_router.dart/0
{'file_path': 'uxr/nav2-usability/scenario_code/lib/skipping-stacks/skipping_stacks_go_router.dart', 'repo_id': 'uxr', 'token_count': 2599}
// The following syntax deactivates a lint for the entire file: // ignore_for_file: avoid_print void main() { /// The following line would normally show a lint warning /// but we can disable the lint rule for this line using the following syntax. var greeting = 'hello world'; // ignore: prefer_final_locals /// The following line would normally show a lint warning /// but we can disable the lint rule for this file using `ignore_for_file`. print(greeting); }
very_good_analysis/example/lib/example.dart/0
{'file_path': 'very_good_analysis/example/lib/example.dart', 'repo_id': 'very_good_analysis', 'token_count': 128}
import 'package:mason/mason.dart'; import 'package:universal_io/io.dart'; /// {@template template} /// Dart class that represents a VeryGoodCLI supported template. /// Each template consists of a [MasonBundle], name, /// and help text describing the template. /// {@endtemplate} abstract class Template { /// {@macro template} const Template({ required this.name, required this.bundle, required this.help, }); /// The name associated with this template. final String name; /// The [MasonBundle] used to generate this template. final MasonBundle bundle; /// The help text shown in the usage information for the CLI. final String help; /// Callback invoked after template generation has completed. Future<void> onGenerateComplete(Logger logger, Directory outputDir); }
very_good_cli/lib/src/commands/create/templates/template.dart/0
{'file_path': 'very_good_cli/lib/src/commands/create/templates/template.dart', 'repo_id': 'very_good_cli', 'token_count': 226}
import 'dart:io'; import 'package:mason/mason.dart'; import 'package:very_good_cli/src/commands/create/templates/templates.dart'; import 'package:very_good_cli/src/logger_extension.dart'; /// {@template flame_game_template} /// A Flame Game template. /// {@endtemplate} class VeryGoodFlameGameTemplate extends Template { /// {@macro flame_game_template} VeryGoodFlameGameTemplate() : super( name: 'flame_game', bundle: veryGoodFlameGameBundle, help: 'Generate a Very Good Flame game.', ); @override Future<void> onGenerateComplete(Logger logger, Directory outputDir) async { await installDartPackages(logger, outputDir); await applyDartFixes(logger, outputDir); _logSummary(logger); } void _logSummary(Logger logger) { logger ..info('\n') ..created('Created a Very Good Game powered by Flame! 🔥🦄') ..info('\n'); } }
very_good_cli/lib/src/commands/create/templates/very_good_flame_game/very_good_flame_game_template.dart/0
{'file_path': 'very_good_cli/lib/src/commands/create/templates/very_good_flame_game/very_good_flame_game_template.dart', 'repo_id': 'very_good_cli', 'token_count': 353}
@Tags(['pull-request-only']) import 'package:build_verify/build_verify.dart'; import 'package:test/test.dart'; void main() { test('ensure_build', expectBuildClean); }
very_good_cli/test/ensure_build_test.dart/0
{'file_path': 'very_good_cli/test/ensure_build_test.dart', 'repo_id': 'very_good_cli', 'token_count': 63}
version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/brick/hooks" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/tool/generator" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/src/my_app" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/e2e" schedule: interval: "daily"
very_good_core/.github/dependabot.yaml/0
{'file_path': 'very_good_core/.github/dependabot.yaml', 'repo_id': 'very_good_core', 'token_count': 212}
export 'pump_app.dart';
very_good_core/brick/__brick__/{{project_name.snakeCase()}}/test/helpers/helpers.dart/0
{'file_path': 'very_good_core/brick/__brick__/{{project_name.snakeCase()}}/test/helpers/helpers.dart', 'repo_id': 'very_good_core', 'token_count': 11}
export 'sample_command.dart'; export 'update_command.dart';
very_good_dart_cli/brick/__brick__/{{project_name.snakeCase()}}/lib/src/commands/commands.dart/0
{'file_path': 'very_good_dart_cli/brick/__brick__/{{project_name.snakeCase()}}/lib/src/commands/commands.dart', 'repo_id': 'very_good_dart_cli', 'token_count': 20}
name: my_cli concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: pull_request: paths: - ".github/workflows/my_cli.yaml" - "lib/**" - "test/**" - "pubspec.yaml" push: branches: - main paths: - ".github/workflows/my_cli.yaml" - "lib/**" - "test/**" - "pubspec.yaml" jobs: semantic-pull-request: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/semantic_pull_request.yml@v1 build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/dart_package.yml@v1 verify-version: runs-on: ubuntu-latest steps: - name: 📚 Git Checkout uses: actions/checkout@v2 - name: 🎯 Setup Dart uses: dart-lang/setup-dart@v1 with: sdk: "stable" - name: 📦 Install Dependencies run: | dart pub get - name: 🔎 Verify version run: dart run test --run-skipped -t version-verify
very_good_dart_cli/src/my_cli/.github/workflows/my_cli.yaml/0
{'file_path': 'very_good_dart_cli/src/my_cli/.github/workflows/my_cli.yaml', 'repo_id': 'very_good_dart_cli', 'token_count': 467}
name: very_good_docs_site concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: push: paths: - .github/workflows/very_good_docs_site.yaml - "brick/**" branches: - main pull_request: paths: - .github/workflows/very_good_docs_site.yaml - "brick/**" branches: - main jobs: brick: runs-on: ubuntu-latest steps: - name: 📚 Git Checkout uses: actions/checkout@v4 - name: 🎯 Setup Dart uses: dart-lang/setup-dart@v1 with: sdk: stable - name: 🧱 Mason Make run: | dart pub global activate mason_cli mason get mason make very_good_docs_site -c brick/config.json -o output --on-conflict overwrite - name: ⚙️ Setup Node uses: actions/setup-node@v4 with: node-version: 18.x - name: 📦 Install Dependencies run: | cd output/test_docs_site npm i - name: ✨ Check Format run: | cd output/test_docs_site npm run format:check - name: 🧹 Lint run: | cd output/test_docs_site npm run lint - name: 👷 Build website run: | cd output/test_docs_site npm run build
very_good_docs_site/.github/workflows/very_good_docs_site.yaml/0
{'file_path': 'very_good_docs_site/.github/workflows/very_good_docs_site.yaml', 'repo_id': 'very_good_docs_site', 'token_count': 659}
version: 2 enable-beta-ecosystems: true updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/src/very_good_flame_game" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/brick/hooks" schedule: interval: "daily" - package-ecosystem: "pub" directory: "/tool/generator" schedule: interval: "daily"
very_good_flame_game/.github/dependabot.yaml/0
{'file_path': 'very_good_flame_game/.github/dependabot.yaml', 'repo_id': 'very_good_flame_game', 'token_count': 186}
export 'components/components.dart'; export 'cubit/cubit.dart'; export 'entities/entities.dart'; export '{{project_name.snakeCase()}}.dart'; export 'view/view.dart';
very_good_flame_game/brick/__brick__/{{project_name.snakeCase()}}/lib/game/game.dart/0
{'file_path': 'very_good_flame_game/brick/__brick__/{{project_name.snakeCase()}}/lib/game/game.dart', 'repo_id': 'very_good_flame_game', 'token_count': 65}
export 'counter_component.dart';
very_good_flame_game/src/very_good_flame_game/lib/game/components/components.dart/0
{'file_path': 'very_good_flame_game/src/very_good_flame_game/lib/game/components/components.dart', 'repo_id': 'very_good_flame_game', 'token_count': 10}
export 'preload/preload_cubit.dart';
very_good_flame_game/src/very_good_flame_game/lib/loading/cubit/cubit.dart/0
{'file_path': 'very_good_flame_game/src/very_good_flame_game/lib/loading/cubit/cubit.dart', 'repo_id': 'very_good_flame_game', 'token_count': 16}
analyzer: exclude: - brick/**
very_good_flutter_package/analysis_options.yaml/0
{'file_path': 'very_good_flutter_package/analysis_options.yaml', 'repo_id': 'very_good_flutter_package', 'token_count': 15}
name: my_plugin_macos concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: pull_request: paths: - ".github/workflows/my_plugin_macos.yaml" - "src/my_plugin/my_plugin_macos/**" push: branches: - main paths: - ".github/workflows/my_plugin_macos.yaml" - "src/my_plugin/my_plugin_macos/**" jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1 with: flutter_channel: stable flutter_version: 3.13.2 working_directory: src/my_plugin/my_plugin_macos
very_good_flutter_plugin/.github/workflows/my_plugin_macos.yaml/0
{'file_path': 'very_good_flutter_plugin/.github/workflows/my_plugin_macos.yaml', 'repo_id': 'very_good_flutter_plugin', 'token_count': 267}
import 'package:flutter/material.dart'; import 'package:{{project_name.snakeCase()}}/{{project_name.snakeCase()}}.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(home: HomePage()); } } class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { String? _platformName; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('{{project_name.pascalCase()}} Example')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ if (_platformName == null) const SizedBox.shrink() else Text( 'Platform Name: $_platformName', style: Theme.of(context).textTheme.headlineSmall, ), const SizedBox(height: 16), ElevatedButton( onPressed: () async { if (!context.mounted) return; try { final result = await getPlatformName(); setState(() => _platformName = result); } catch (error) { if (!context.mounted) return; ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: Theme.of(context).primaryColor, content: Text('$error'), ), ); } }, child: const Text('Get Platform Name'), ), ], ), ), ); } }
very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{project_name.snakeCase()}}/example/lib/main.dart/0
{'file_path': 'very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{project_name.snakeCase()}}/example/lib/main.dart', 'repo_id': 'very_good_flutter_plugin', 'token_count': 898}
import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:my_plugin_linux/my_plugin_linux.dart'; import 'package:my_plugin_platform_interface/my_plugin_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('MyPluginLinux', () { const kPlatformName = 'Linux'; late MyPluginLinux myPlugin; late List<MethodCall> log; setUp(() async { myPlugin = MyPluginLinux(); log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(myPlugin.methodChannel, (methodCall) async { log.add(methodCall); switch (methodCall.method) { case 'getPlatformName': return kPlatformName; default: return null; } }); }); test('can be registered', () { MyPluginLinux.registerWith(); expect(MyPluginPlatform.instance, isA<MyPluginLinux>()); }); test('getPlatformName returns correct name', () async { final name = await myPlugin.getPlatformName(); expect( log, <Matcher>[isMethodCall('getPlatformName', arguments: null)], ); expect(name, equals(kPlatformName)); }); }); }
very_good_flutter_plugin/src/my_plugin/my_plugin_linux/test/my_plugin_linux_test.dart/0
{'file_path': 'very_good_flutter_plugin/src/my_plugin/my_plugin_linux/test/my_plugin_linux_test.dart', 'repo_id': 'very_good_flutter_plugin', 'token_count': 502}
import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:flutter/services.dart'; import 'package:my_plugin_platform_interface/my_plugin_platform_interface.dart'; /// An implementation of [MyPluginPlatform] that uses method channels. class MethodChannelMyPlugin extends MyPluginPlatform { /// The method channel used to interact with the native platform. @visibleForTesting final methodChannel = const MethodChannel('my_plugin'); @override Future<String?> getPlatformName() { return methodChannel.invokeMethod<String>('getPlatformName'); } }
very_good_flutter_plugin/src/my_plugin/my_plugin_platform_interface/lib/src/method_channel_my_plugin.dart/0
{'file_path': 'very_good_flutter_plugin/src/my_plugin/my_plugin_platform_interface/lib/src/method_channel_my_plugin.dart', 'repo_id': 'very_good_flutter_plugin', 'token_count': 156}
import 'package:very_good_performance/src/models/models.dart'; class Scorer { static Score score(Report report, Configuration configuration) { final perfMetrics = configuration.performanceMetrics; return Score( missedFrames: _rating( value: report.missedFrameBuildBudgetCount, warning: perfMetrics.missedFramesThreshold.warning, error: perfMetrics.missedFramesThreshold.error, ), averageBuildRate: _rating( value: report.averageFrameBuildTimeMillis, warning: perfMetrics .averageFrameBuildRateThreshold.warningTimeInMilliseconds, error: perfMetrics.averageFrameBuildRateThreshold.errorTimeInMilliseconds, ), worstFrameBuildRate: _rating( value: report.worstFrameBuildTimeMillis, warning: perfMetrics.worstFrameBuildRateThreshold.warningTimeInMilliseconds, error: perfMetrics.worstFrameBuildRateThreshold.errorTimeInMilliseconds, ), ); } static Rating _rating({ required num value, required num warning, required num error, }) { if (value < warning) { return Rating.success; } else if (value >= warning && value < error) { return Rating.warning; } return Rating.failure; } }
very_good_performance/lib/src/scorer.dart/0
{'file_path': 'very_good_performance/lib/src/scorer.dart', 'repo_id': 'very_good_performance', 'token_count': 484}
import 'package:flutter/foundation.dart'; class Config { /// Unicorn Spawn static const unicornSpawnThreshold = 50.0; static const unicornInitialSpawnThreshold = 30.0; static const unicornVaryThresholdBy = 0.5; /// Food Spawn static const foodInitialSpawnThreshold = 10.0; static const foodSpawnThreshold = 5.0; static const foodVaryThresholdBy = 0.2; static const foodSpawnDecayRateBaby = 0.08; static const foodSpawnDecayRateChild = 0.12; static const foodSpawnDecayRateTeen = 0.16; static const foodSpawnDecayRateAdult = 0.30; /// Fullness static const fullnessDecreaseInterval = 0.5; static const fullnessDecreaseFactor = StageProperty( baby: 0.0050, child: 0.00625, teen: 0.0083, adult: 0.0125, ); /// Enjoyment static const enjoymentDecreaseInterval = 0.5; static const enjoymentDecreaseFactor = StageProperty( baby: 0.0100, child: 0.0050, teen: 0.0030, adult: 0.0015, ); /// Feeding static const fullnessFeedFactor = StageProperty( baby: 0.45, child: 0.25, teen: 0.18, adult: 0.25, ); static const double positiveImpactOnEnjoyment = 0.6; static const double negativeImpactOnEnjoyment = -0.01; /// Petting static const petEnjoymentIncrease = StageProperty( baby: 0.3, child: 0.2, teen: 0.15, adult: 0.1, ); static const petThrottleDuration = 1.0; /// Evolving static const double happinessThresholdToEvolve = 0.6; static const int timesThatMustBeFedToEvolve = 5; /// Leaving static const double happinessThresholdToLeave = 0.1; /// Moving static const double movingEvaluationCycle = 5; static const double probabilityToStartMoving = 0.8; /// Wander static const double circleDistance = 10; static const double maximumAngleDegree = 15; static const double startingAngleDegree = 0; /// Despawn static const double cakeDespawnTime = 30; static const double lollipopDespawnTime = 23; static const double iceCreamDespawnTime = 16; static const double pancakeDespawnTime = 9; } @immutable class StageProperty<T> { const StageProperty({ required this.baby, required this.child, required this.teen, required this.adult, }); final T baby; final T child; final T teen; final T adult; }
very_good_ranch/lib/config.dart/0
{'file_path': 'very_good_ranch/lib/config.dart', 'repo_id': 'very_good_ranch', 'token_count': 775}
import 'package:flame/components.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:very_good_ranch/config.dart'; import 'package:very_good_ranch/game/entities/unicorn/unicorn.dart'; class EnjoymentDecreasingBehavior extends Behavior<Unicorn> { @override Future<void> onLoad() async { await add( TimerComponent( period: Config.enjoymentDecreaseInterval, repeat: true, onTick: _decreaseEnjoyment, ), ); } void _decreaseEnjoyment() { parent.enjoyment.decreaseBy(parent.evolutionStage.enjoymentDecreaseFactor); } } extension on UnicornEvolutionStage { /// Percentage that of enjoyment lost every /// [Config.enjoymentDecreaseInterval]. double get enjoymentDecreaseFactor { switch (this) { case UnicornEvolutionStage.baby: return Config.enjoymentDecreaseFactor.baby; case UnicornEvolutionStage.child: return Config.enjoymentDecreaseFactor.child; case UnicornEvolutionStage.teen: return Config.enjoymentDecreaseFactor.teen; case UnicornEvolutionStage.adult: return Config.enjoymentDecreaseFactor.adult; } } }
very_good_ranch/lib/game/entities/unicorn/behaviors/enjoyment_decreasing_behavior.dart/0
{'file_path': 'very_good_ranch/lib/game/entities/unicorn/behaviors/enjoyment_decreasing_behavior.dart', 'repo_id': 'very_good_ranch', 'token_count': 431}
import 'package:flame/game.dart'; import 'package:flutter/material.dart'; import 'package:very_good_ranch/game_menu/game_menu.dart'; import 'package:very_good_ranch/l10n/l10n.dart'; class GameView<GameType extends FlameGame> extends StatelessWidget { const GameView({super.key, required this.game}); final GameType game; @override Widget build(BuildContext context) { final l10n = context.l10n; return SafeArea( bottom: false, child: LayoutBuilder( builder: (context, constraints) { final biggest = constraints.biggest; return Stack( fit: StackFit.expand, children: [ GameWidget<GameType>( game: game, ), Positioned( top: biggest.height * 0.08, right: biggest.width * 0.04, child: IconButton( tooltip: l10n.settings, color: const Color(0xFF107161), icon: const Icon( Icons.tune, size: 36, ), onPressed: () async { game.pauseEngine(); await GameMenuDialog.open(context); game.resumeEngine(); }, ), ) ], ); }, ), ); } }
very_good_ranch/lib/game/widgets/game_view.dart/0
{'file_path': 'very_good_ranch/lib/game/widgets/game_view.dart', 'repo_id': 'very_good_ranch', 'token_count': 748}
import 'package:bloc/bloc.dart'; import 'package:flutter/widgets.dart'; import 'package:ranch_components/ranch_components.dart'; import 'package:ranch_flame/ranch_flame.dart'; import 'package:ranch_sounds/ranch_sounds.dart'; import 'package:very_good_ranch/loading/loading.dart'; class PreloadCubit extends Cubit<PreloadState> { PreloadCubit(this.images, this.sounds) : super(const PreloadState.initial()); final UnprefixedImages images; final RanchSoundPlayer sounds; /// Load items sequentially allows display of what is being loaded Future<void> loadSequentially() async { final phases = <PreloadPhase>[ PreloadPhase( 'sounds', () => sounds.preloadAssets([RanchSound.sunsetMemory]), ), PreloadPhase( 'environment', () => BackgroundComponent.preloadAssets(images), ), PreloadPhase('food', () => FoodComponent.preloadAssets(images)), PreloadPhase( 'baby_unicorns', () => BabyUnicornComponent.preloadAssets(images), ), PreloadPhase( 'child_unicorns', () => ChildUnicornComponent.preloadAssets(images), ), PreloadPhase( 'teen_unicorns', () => TeenUnicornComponent.preloadAssets(images), ), PreloadPhase( 'adult_unicorns', () => AdultUnicornComponent.preloadAssets(images), ), ]; emit(state.startLoading(phases.length)); for (final phase in phases) { emit(state.onStartPhase(phase.label)); // Throttle phases to take at least 1/5 seconds await Future.wait([ Future.delayed(Duration.zero, phase.start), Future<void>.delayed(const Duration(milliseconds: 200)), ]); emit(state.onFinishPhase()); } } @override Future<void> close() async { await sounds.dispose(); return super.close(); } } @immutable class PreloadPhase { const PreloadPhase(this.label, this.start); final String label; final ValueGetter<Future<void>> start; }
very_good_ranch/lib/loading/cubit/preload/preload_cubit.dart/0
{'file_path': 'very_good_ranch/lib/loading/cubit/preload/preload_cubit.dart', 'repo_id': 'very_good_ranch', 'token_count': 778}
import 'dart:async'; import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flutter/material.dart'; import 'package:ranch_components/ranch_components.dart'; /// {@template rainbow_drop} /// A [PositionComponent] that renders a rainbow drop like effect that "carries" /// a target into the game. /// {@endtemplate} class RainbowDrop extends PositionComponent with HasGameRef { /// {@macro rainbow_drop} RainbowDrop({ /// The position that the [target] will be "dropped". required Vector2 position, /// The target that the drop will "carry" into the game. required PositionComponent target, /// The target sprite. required HasPaint sprite, }) : _target = target, _sprite = sprite, super(position: position, anchor: Anchor.bottomCenter, priority: 999); final PositionComponent _target; final HasPaint _sprite; static const _colors = [ Color(0xFFEF6C6C), Color(0xFFEDB069), Color(0xFFFFDD99), Color(0xFF99FDFF), Color(0xFF51C7EC), Color(0xFF805BD4), ]; @override Future<void> onLoad() async { final targetY = y; height = gameRef.size.y + position.y; y = -height; const baseTime = .4; final segmentSize = _target.size.y / _colors.length; unawaited( Future<void>.delayed(const Duration(milliseconds: 500), () { parent?.add( ConfettiComponent( position: position + Vector2(_target.size.x / 2, 0), confettiSize: segmentSize, priority: _sprite.priority + 1, ), ); }), ); unawaited( Future<void>.delayed( const Duration(milliseconds: 550), () { _sprite.setOpacity(0); parent?.add( _target..position = Vector2(x, targetY), ); _sprite.add( OpacityEffect.to( 1, CurvedEffectController(baseTime, Curves.easeOutCubic), ), ); removeFromParent(); }, ), ); await addAll( [ ClipComponent.rect( size: Vector2(segmentSize * Colors.accents.length, height), children: [ for (var i = 0; i < _colors.length; i++) RectangleComponent( paint: Paint()..color = _colors[i], size: Vector2(segmentSize, height), position: Vector2(segmentSize * i, 0), children: [ MoveEffect.to( Vector2(segmentSize * i, height), SequenceEffectController( [ PauseEffectController(baseTime, progress: 0), CurvedEffectController(baseTime, Curves.easeOutCubic), ], ), ), OpacityEffect.to( 0, SequenceEffectController( [ PauseEffectController(baseTime, progress: 0), CurvedEffectController(baseTime, Curves.easeOut), ], ), ), ], ), ], ), MoveEffect.to( Vector2(x, targetY + _target.size.y), CurvedEffectController( baseTime, Curves.easeOutCubic, ), ), ], ); } }
very_good_ranch/packages/ranch_components/lib/src/components/fx/rainbow_drop.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/lib/src/components/fx/rainbow_drop.dart', 'repo_id': 'very_good_ranch', 'token_count': 1745}
import 'dart:ui'; import 'package:dashbook/dashbook.dart'; import 'package:flame/components.dart'; import 'package:flame/flame.dart'; import 'package:flame/game.dart'; import 'package:ranch_components/ranch_components.dart'; class EvolutionComponentExample extends FlameGame { EvolutionComponentExample() { images.prefix = ''; Flame.images.prefix = ''; } @override Future<void> onLoad() async { await add( PositionComponent( position: size / 2, children: [ BabyUnicornComponent(), ], ), ); } void evolve() { final entity = firstChild<PositionComponent>()!; final child = entity.firstChild<PositionComponent>()!; late PositionComponent to; if (child is BabyUnicornComponent) { to = ChildUnicornComponent(); } else if (child is ChildUnicornComponent) { to = TeenUnicornComponent(); } else if (child is TeenUnicornComponent) { to = AdultUnicornComponent(); } else if (child is AdultUnicornComponent) { to = BabyUnicornComponent(); } entity.add( Evolution( from: child, to: to, ), ); } @override Color backgroundColor() => const Color(0xFF52C1B1); } void addEvolutionComponentStories(Dashbook dashbook) { dashbook.storiesOf('Evolution').add( 'basic', (context) { final game = EvolutionComponentExample(); context.action('evolve', (_) { game.evolve(); }); return GameWidget(game: game); }, ); }
very_good_ranch/packages/ranch_components/sandbox/lib/stories/evolution_component/stories.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/sandbox/lib/stories/evolution_component/stories.dart', 'repo_id': 'very_good_ranch', 'token_count': 591}
import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:ranch_components/src/components/background/background_elements.dart'; import '../../helpers/helpers.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester( () => TestGame(center: true), ); group('Background elements', () { flameTester.testGameWidget( 'sets the priority to the bottom center of the element', setUp: (game, tester) async { final barn = Barn(); await game.ensureAdd(barn); }, verify: (game, tester) async { final barn = game.firstChild<Barn>()!; expect( barn.priority, equals(barn.positionOfAnchor(Anchor.bottomCenter).y), ); }, ); group('BackgroundTreeType', () { test('getBackgroundElement', () { expect( BackgroundTreeType.tall.getBackgroundElement(Vector2.zero()), isA<TallTree>(), ); expect( BackgroundTreeType.short.getBackgroundElement(Vector2.zero()), isA<ShortTree>(), ); expect( BackgroundTreeType.lined.getBackgroundElement(Vector2.zero()), isA<LinedTree>(), ); expect( BackgroundTreeType.linedShort.getBackgroundElement(Vector2.zero()), isA<LinedTreeShort>(), ); }); }); group('Barn', () { flameTester.testGameWidget( 'renders a Barn', setUp: (game, tester) async { final barn = Barn(); await game.ensureAdd(barn); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/barn.png'), ); }, ); }); group('Sheep', () { flameTester.testGameWidget( 'renders a Sheep', setUp: (game, tester) async { await game.ensureAdd(Sheep()); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/sheep.png'), ); }, ); }); group('SheepSmall', () { flameTester.testGameWidget( 'renders a SheepSmall', setUp: (game, tester) async { await game.ensureAdd(SheepSmall()); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/sheep_small.png'), ); }, ); }); group('Cow', () { flameTester.testGameWidget( 'renders a Cow', setUp: (game, tester) async { await game.ensureAdd(Cow()); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/cow.png'), ); }, ); }); group('LinedTree', () { flameTester.testGameWidget( 'renders a LinedTree', setUp: (game, tester) async { final linedTree = LinedTree(); await game.ensureAdd(linedTree); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/lined_tree.png'), ); }, ); }); group('LinedTreeShort', () { flameTester.testGameWidget( 'renders a LinedTreeShort', setUp: (game, tester) async { final linedTree = LinedTreeShort(); await game.ensureAdd(linedTree); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/lined_tree_short.png'), ); }, ); }); group('TallTree', () { flameTester.testGameWidget( 'renders a TallTree', setUp: (game, tester) async { final tallTree = TallTree(); await game.ensureAdd(tallTree); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/tall_tree.png'), ); }, ); }); group('ShortTree', () { flameTester.testGameWidget( 'renders a ShortTree', setUp: (game, tester) async { final shortTree = ShortTree(); await game.ensureAdd(shortTree); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/short_tree.png'), ); }, ); }); group('Grass', () { flameTester.testGameWidget( 'renders a Grass', setUp: (game, tester) async { final grass = Grass(); await game.ensureAdd(grass); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/grass.png'), ); }, ); }); group('FlowerSolo', () { flameTester.testGameWidget( 'renders a FlowerSolo', setUp: (game, tester) async { final flowerSolo = FlowerSolo(); await game.ensureAdd(flowerSolo); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/flowersolo.png'), ); }, ); }); group('FlowerDuo', () { flameTester.testGameWidget( 'renders a FlowerDuo', setUp: (game, tester) async { final flowerDuo = FlowerDuo(); await game.ensureAdd(flowerDuo); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/flowerduo.png'), ); }, ); }); group('FlowerGroup', () { flameTester.testGameWidget( 'renders a FlowerGroup', setUp: (game, tester) async { final flowerGroup = FlowerGroup(); await game.ensureAdd(flowerGroup); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/elements/flowergroup.png'), ); }, ); }); }); }
very_good_ranch/packages/ranch_components/test/components/background/background_elements_test.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/test/components/background/background_elements_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 3211}
import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:ranch_components/ranch_components.dart'; void main() { group('StarBustComponent', () { testWithFlameGame('creates particles on load', (game) async { await game.ensureAdd(StarBurstComponent(starSize: 10)); expect( game.descendants().whereType<ParticleSystemComponent>().length, greaterThan(0), ); }); testWithFlameGame( 'is removed after all particles have expired', (game) async { await game.ensureAdd(StarBurstComponent(starSize: 10)); expect( game.descendants().whereType<ParticleSystemComponent>().length, greaterThan(0), ); game ..updateTree(2) // Runs enough time for the particles to expire. ..updateTree(0); // Component is removed on the next tick. await game.ready(); expect( game.children.length, 0, ); }, ); testGolden( 'star renders correctly', (game) async { await game.ensureAdd(Star(100)..position = Vector2.all(200)); }, goldenFile: 'golden/star_burst/star.png', ); }); }
very_good_ranch/packages/ranch_components/test/components/fx/star_burst_component_test.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/test/components/fx/star_burst_component_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 534}
import 'dart:collection'; import 'dart:math'; import 'package:equatable/equatable.dart'; /// {@template rarity} /// A [Rarity] describes the rarity of a instance of [T]. /// {@endtemplate} class Rarity<T> extends Equatable { /// {@macro rarity} const Rarity(this.value, this.weight); /// The value of the rarity. final T value; /// The weight of the rarity. final int weight; @override List<Object?> get props => [value, weight]; } /// {@template rarity_list} /// A [RarityList] is a list of [Rarity]s. That can be used to get a random /// [Rarity] from the list. /// {@endtemplate} class RarityList<T> { /// {@macro rarity_list} RarityList(List<Rarity<T>> rarities) : _rarities = rarities..sort((a, b) => a.weight < b.weight ? 1 : -1), assert( rarities.fold<int>(0, _raritySum) == 100, 'The sum of the rarities weight has to equal 100%', ) { _probabilities = _rarities.map((rare) { final filler = 100 - _rarities.fold<int>(0, _raritySum); return List.filled(rare.weight == 0 ? filler : rare.weight, rare); }).fold<List<Rarity<T>>>(<Rarity<T>>[], (p, e) => p..addAll(e)); } /// List of rarities. Sorted by weight. List<Rarity<T>> get rarities => UnmodifiableListView(_rarities); late final List<Rarity<T>> _rarities; /// List of a total of 100 items based on the weight value of each rarity. List<Rarity<T>> get probabilities => UnmodifiableListView(_probabilities); late final List<Rarity<T>> _probabilities; /// Returns a random [Rarity] item. T getRandom([Random? rnd]) { final index = (rnd ?? Random()).nextInt(100); return _probabilities[index].value; } static int _raritySum<T>(int sum, Rarity<T> rarity) => sum + rarity.weight; }
very_good_ranch/packages/ranch_flame/lib/src/rarity_list.dart/0
{'file_path': 'very_good_ranch/packages/ranch_flame/lib/src/rarity_list.dart', 'repo_id': 'very_good_ranch', 'token_count': 652}
/// GENERATED CODE - DO NOT MODIFY BY HAND /// ***************************************************** /// FlutterGen /// ***************************************************** // coverage:ignore-file // ignore_for_file: type=lint // ignore_for_file: directives_ordering,unnecessary_import import 'package:flutter/widgets.dart'; class $AssetsMusicGen { const $AssetsMusicGen(); /// File path: assets/music/game_background.wav String get gameBackground => 'assets/music/game_background.wav'; /// File path: assets/music/start_background.wav String get startBackground => 'assets/music/start_background.wav'; /// File path: assets/music/sunset_memory.mp3 String get sunsetMemory => 'assets/music/sunset_memory.mp3'; /// File path: assets/music/sunset_memory_license.txt String get sunsetMemoryLicense => 'assets/music/sunset_memory_license.txt'; } class Assets { Assets._(); static const $AssetsMusicGen music = $AssetsMusicGen(); } class AssetGenImage { const AssetGenImage(this._assetName); final String _assetName; Image image({ Key? key, AssetBundle? bundle, ImageFrameBuilder? frameBuilder, ImageErrorWidgetBuilder? errorBuilder, String? semanticLabel, bool excludeFromSemantics = false, double? scale, double? width, double? height, Color? color, Animation<double>? opacity, BlendMode? colorBlendMode, BoxFit? fit, AlignmentGeometry alignment = Alignment.center, ImageRepeat repeat = ImageRepeat.noRepeat, Rect? centerSlice, bool matchTextDirection = false, bool gaplessPlayback = false, bool isAntiAlias = false, String? package, FilterQuality filterQuality = FilterQuality.low, int? cacheWidth, int? cacheHeight, }) { return Image.asset( _assetName, key: key, bundle: bundle, frameBuilder: frameBuilder, errorBuilder: errorBuilder, semanticLabel: semanticLabel, excludeFromSemantics: excludeFromSemantics, scale: scale, width: width, height: height, color: color, opacity: opacity, colorBlendMode: colorBlendMode, fit: fit, alignment: alignment, repeat: repeat, centerSlice: centerSlice, matchTextDirection: matchTextDirection, gaplessPlayback: gaplessPlayback, isAntiAlias: isAntiAlias, package: package, filterQuality: filterQuality, cacheWidth: cacheWidth, cacheHeight: cacheHeight, ); } String get path => _assetName; String get keyName => _assetName; }
very_good_ranch/packages/ranch_sounds/lib/gen/assets.gen.dart/0
{'file_path': 'very_good_ranch/packages/ranch_sounds/lib/gen/assets.gen.dart', 'repo_id': 'very_good_ranch', 'token_count': 880}
import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:ranch_ui/ranch_ui.dart'; /// {@template modal_theme} /// An inherited widget that defines visual properties for /// [Modal]s in this widget's subtree. /// {@endtemplate} class ModalTheme extends InheritedWidget { /// {@macro modal_theme} const ModalTheme({ super.key, required super.child, required this.data, }); /// The actual values for the theme final ModalThemeData data; /// The default theme data for [ModalTheme] static final defaultTheme = ModalThemeData( outerPadding: const EdgeInsets.all(16), innerPadding: const EdgeInsets.only( top: 16, left: 16, bottom: 24, right: 16, ), sliderThemeData: const SliderThemeData( activeTrackColor: HoverMaterialStateColor(0xFF674FB2), inactiveTrackColor: HoverMaterialStateColor(0xFFFFF4E0), thumbColor: HoverMaterialStateColor(0xFF674FB2), overlayColor: HoverMaterialStateColor(0x22674FB2), ), dividerThemeData: const DividerThemeData( color: Color(0x14000000), space: 32, ), elevatedButtonThemeData: ElevatedButtonThemeData( style: ButtonStyle( backgroundColor: const HoverMaterialStateColor( 0xFF805BD4, hover: Color(0xFF99FDFF), ), overlayColor: const HoverMaterialStateColor( 0xFF805BD4, hover: Color(0xFF99FDFF), ), foregroundColor: const HoverMaterialStateColor( 0xFFFFFFFF, hover: Color(0xFF56469B), ), padding: const MaterialStatePropertyAll( EdgeInsets.symmetric( horizontal: 24, vertical: 23, ), ), shape: const MaterialStatePropertyAll( RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(1.54), ), ), ), textStyle: MaterialStatePropertyAll( RanchUITheme.minorFontTextStyle.copyWith( fontSize: 18, height: 1.33, color: const Color(0xFFFFFFFF), fontWeight: FontWeight.w400, ), ), ), ), contentResizeDuration: const Duration(milliseconds: 100), sizeConstraints: const BoxConstraints( maxWidth: 296, minHeight: 200, ), cardDecoration: const BoxDecoration( boxShadow: [ BoxShadow( color: Color(0x26000000), blurRadius: 52, ), BoxShadow( color: Color(0x26000000), blurRadius: 28, ), BoxShadow( color: Color(0x26000000), blurRadius: 18, ), ], ), cardBorderRadius: BorderRadius.circular(16), cardColor: const Color(0xFFFFF4E0), closeButtonDecoration: BoxDecoration( border: Border.all(color: const Color(0xFF805BD4), width: 4), borderRadius: BorderRadius.circular(40), color: const Color(0xFFFFFFFF), boxShadow: const [ BoxShadow( color: Color(0x26000000), blurRadius: 8, offset: Offset(0, 1), ), BoxShadow( color: Color(0x1E000000), blurRadius: 4, offset: Offset(0, 2), ), BoxShadow( color: Color(0x19000000), blurRadius: 2, offset: Offset(0, 1), ), ], ), closeButtonIconColor: const Color(0xFF805BD4), titleTextStyle: RanchUITheme.mainFontTextStyle.copyWith( fontSize: 32, height: 1.25, letterSpacing: 1.28, color: const Color(0xFF674FB2), shadows: [ const Shadow( color: Color(0xFF9CFFFE), offset: Offset(0, 1), ), ], fontWeight: FontWeight.w400, ), titleTextAlign: TextAlign.center, ); /// The closest instance of this theme that encloses the given context. /// /// If there is no enclosing [ModalTheme] widget, then /// [ModalTheme.defaultTheme] is used. static ModalThemeData of(BuildContext context) { final theme = context.dependOnInheritedWidgetOfExactType<ModalTheme>(); return theme?.data ?? defaultTheme; } @override bool updateShouldNotify(ModalTheme oldWidget) => data != oldWidget.data; } /// {@template modal_theme_data} /// Defines default property values for descendant [Modal] widgets. /// {@endtemplate} class ModalThemeData extends Equatable { /// {@macro modal_theme_data} const ModalThemeData({ required this.outerPadding, required this.innerPadding, required this.sliderThemeData, required this.dividerThemeData, required this.elevatedButtonThemeData, required this.contentResizeDuration, required this.sizeConstraints, required this.cardDecoration, required this.cardBorderRadius, required this.cardColor, required this.closeButtonDecoration, required this.closeButtonIconColor, required this.titleTextStyle, required this.titleTextAlign, }); /// The padding outside the modal card final EdgeInsets outerPadding; /// The padding inside the modal card final EdgeInsets innerPadding; /// Default theme for sliders within the modal final SliderThemeData sliderThemeData; /// Default theme for dividers within the modal final DividerThemeData dividerThemeData; /// Default theme for elevated buttons within the modal final ElevatedButtonThemeData elevatedButtonThemeData; /// Resize animation duration for when modal content size changes final Duration contentResizeDuration; /// Size constraints for the modal card final BoxConstraints sizeConstraints; // card style /// Decoration for the modal card final BoxDecoration cardDecoration; /// Radius for the corners of the modal final BorderRadius cardBorderRadius; /// The background color for the modal card final Color cardColor; // close button /// Decoration for the close button final BoxDecoration closeButtonDecoration; /// The color of the close icon final Color closeButtonIconColor; // title /// Style for the title text final TextStyle titleTextStyle; /// Title text Align final TextAlign titleTextAlign; @override List<Object?> get props => [ outerPadding, innerPadding, sliderThemeData, dividerThemeData, elevatedButtonThemeData, contentResizeDuration, sizeConstraints, cardDecoration, cardBorderRadius, cardColor, closeButtonDecoration, closeButtonIconColor, titleTextStyle, titleTextAlign ]; } /// {@template hover_state_color} /// A [MaterialStateColor] that resolves to [hover] if there is a /// [MaterialState.hovered] and hover is not null. Otherwise resovles to /// the default [value]. /// {@endtemplate} class HoverMaterialStateColor extends MaterialStateColor { /// {@macro hover_state_color} const HoverMaterialStateColor(super.defaultValue, {this.hover}); /// The color to be resolved to when the user hovers. final Color? hover; @override Color resolve(Set<MaterialState> states) { final hover = this.hover; if (hover != null && (states.contains(MaterialState.hovered) || states.contains(MaterialState.pressed))) { return hover; } return Color(value); } }
very_good_ranch/packages/ranch_ui/lib/src/widgets/modal/theme.dart/0
{'file_path': 'very_good_ranch/packages/ranch_ui/lib/src/widgets/modal/theme.dart', 'repo_id': 'very_good_ranch', 'token_count': 2914}
import 'package:dashbook/dashbook.dart'; import 'package:flutter/widgets.dart'; import 'package:ranch_ui/ranch_ui.dart'; void addBoardButtonStories(Dashbook dashbook) { dashbook.storiesOf('BoardButton').add('Playground', (context) { return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ const BoardButton( child: Text('Play'), ), BoardButtonTheme.minor( child: const BoardButton( child: Text('Settings'), ), ), ], ); }); }
very_good_ranch/packages/ranch_ui/sandbox/lib/stories/board_button/stories.dart/0
{'file_path': 'very_good_ranch/packages/ranch_ui/sandbox/lib/stories/board_button/stories.dart', 'repo_id': 'very_good_ranch', 'token_count': 256}
// ignore_for_file: cascade_invocations import 'package:flame/input.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:very_good_ranch/game/behaviors/behaviors.dart'; import '../../helpers/helpers.dart'; class _TestEntity extends Entity { _TestEntity({super.behaviors}) : super(size: Vector2.all(32)); } class _TestThresholdDraggingBehavior extends ThresholdDraggableBehavior { _TestThresholdDraggingBehavior({ required this.handleReallyDragStart, required this.handleReallyDragUpdate, }); @override double get threshold => 99; final ValueSetter<DragStartInfo> handleReallyDragStart; final ValueSetter<DragUpdateInfo> handleReallyDragUpdate; @override bool onReallyDragStart(DragStartInfo info) { super.onReallyDragStart(info); handleReallyDragStart(info); return false; } @override bool onReallyDragUpdate(DragUpdateInfo info) { super.onReallyDragUpdate(info); handleReallyDragUpdate(info); return false; } } void main() { final flameTester = FlameTester(TestGame.new); group('ThresholdDraggableBehavior', () { DragStartInfo? lastDragStartInfo; DragUpdateInfo? lastDragUpdateInfo; setUp(() { lastDragStartInfo = null; lastDragUpdateInfo = null; }); flameTester.testGameWidget( 'on drag within threshold', setUp: (game, tester) async { final entity = _TestEntity( behaviors: [ _TestThresholdDraggingBehavior( handleReallyDragStart: (info) { lastDragStartInfo = info; }, handleReallyDragUpdate: (info) { lastDragUpdateInfo = info; }, ), ], ); await game.ensureAdd(entity); await game.ready(); }, verify: (game, tester) async { await tester.flingFrom( Offset.zero, const Offset(0, 90), 100, ); expect(lastDragStartInfo, isNull); expect(lastDragUpdateInfo, isNull); }, ); flameTester.testGameWidget( 'on drag beyond threshold', setUp: (game, tester) async { late final _TestEntity entity; entity = _TestEntity( behaviors: [ _TestThresholdDraggingBehavior( handleReallyDragStart: (info) { lastDragStartInfo = info; }, handleReallyDragUpdate: (info) { entity.position.add(info.delta.game); lastDragUpdateInfo = info; }, ), ], ); await game.ensureAdd(entity); await game.ready(); }, verify: (game, tester) async { await tester.flingFrom( Offset.zero, const Offset(0, 100), 100, ); expect( lastDragStartInfo?.eventPosition.viewport, Vector2.zero(), ); expect( lastDragUpdateInfo?.eventPosition.viewport, Vector2(0, 100), ); lastDragStartInfo = null; lastDragUpdateInfo = null; game.pauseEngine(); await tester.pumpAndSettle(); game.resumeEngine(); await tester.flingFrom( const Offset(0, 100), const Offset(100, 0), 100, ); expect( lastDragStartInfo?.eventPosition.viewport, Vector2(0, 100), ); expect( lastDragUpdateInfo?.eventPosition.viewport, Vector2(100, 100), ); }, ); }); }
very_good_ranch/test/game/behaviors/threshold_draggable_behavior_test.dart/0
{'file_path': 'very_good_ranch/test/game/behaviors/threshold_draggable_behavior_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 1701}
// ignore_for_file: cascade_invocations import 'package:flame/extensions.dart'; import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:ranch_components/ranch_components.dart'; import 'package:very_good_ranch/config.dart'; import 'package:very_good_ranch/game/entities/food/food.dart'; import 'package:very_good_ranch/game/entities/unicorn/behaviors/behaviors.dart'; import 'package:very_good_ranch/game/entities/unicorn/unicorn.dart'; import 'package:very_good_ranch/game/game.dart'; import '../../../../helpers/helpers.dart'; class _MockFood extends Mock implements Food {} class _MockUnicornPercentage extends Mock implements UnicornPercentage {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester<VeryGoodRanchGame>( () => VeryGoodRanchGame(blessingBloc: MockBlessingBloc()), ); group('FoodCollidingBehavior', () { group('does not remove the food', () { test('while it is being dragged', () { final foodCollidingBehavior = FoodCollidingBehavior(); final food = _MockFood(); when(() => food.wasDragged).thenReturn(false); when(() => food.beingDragged).thenReturn(true); when(() => food.isRemoving).thenReturn(false); foodCollidingBehavior.onCollision(<Vector2>{Vector2.zero()}, food); verifyNever(food.removeFromParent); }); test('while it was not being dragged before', () { final foodCollidingBehavior = FoodCollidingBehavior(); final food = _MockFood(); when(() => food.wasDragged).thenReturn(false); when(() => food.beingDragged).thenReturn(false); when(() => food.isRemoving).thenReturn(false); foodCollidingBehavior.onCollision(<Vector2>{Vector2.zero()}, food); verifyNever(food.removeFromParent); }); test('when it as used', () { final foodCollidingBehavior = FoodCollidingBehavior(); final food = _MockFood(); when(() => food.beingDragged).thenReturn(false); when(() => food.wasDragged).thenReturn(true); when(() => food.isRemoving).thenReturn(true); foodCollidingBehavior.onCollision(<Vector2>{Vector2.zero()}, food); verifyNever(food.removeFromParent); }); flameTester.test( 'while unicorn is leaving', (game) async { final foodCollidingBehavior = FoodCollidingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), behaviors: [ foodCollidingBehavior, ], )..isLeaving = true; await game.background.ensureAdd(unicorn); final food = _MockFood(); when(() => food.wasDragged).thenReturn(false); when(() => food.beingDragged).thenReturn(false); foodCollidingBehavior.onCollision(<Vector2>{Vector2.zero()}, food); verifyNever(food.removeFromParent); }, ); }); flameTester.test( 'removes the food from parent when it was dragged', (game) async { final foodCollidingBehavior = FoodCollidingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), unicornComponent: ChildUnicornComponent(), behaviors: [ foodCollidingBehavior, ], )..isLeaving = false; await game.background.ensureAdd(unicorn); final food = _MockFood(); when(() => food.beingDragged).thenReturn(false); when(() => food.wasDragged).thenReturn(true); when(() => food.isRemoving).thenReturn(false); when(() => food.type).thenReturn(FoodType.lollipop); foodCollidingBehavior.onCollision(<Vector2>{Vector2.zero()}, food); verify(food.removeFromParent).called(1); }, ); group('feeding unicorn impacts enjoyment', () { group('with the right type of food', () { for (final evolutionStage in UnicornEvolutionStage.values) { flameTester.test( '${evolutionStage.name} prefers ' '${evolutionStage.preferredFoodType.name}', (game) async { final preferredFoodType = evolutionStage.preferredFoodType; final enjoyment = _MockUnicornPercentage(); final foodCollidingBehavior = FoodCollidingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), unicornComponent: evolutionStage.componentForEvolutionStage(), behaviors: [ foodCollidingBehavior, ], enjoyment: enjoyment, )..isLeaving = false; await game.background.ensureAdd(unicorn); final food = _MockFood(); when(() => food.type).thenReturn(preferredFoodType); when(() => food.wasDragged).thenReturn(true); when(() => food.beingDragged).thenReturn(false); when(() => food.isRemoving).thenReturn(false); foodCollidingBehavior.onCollision({Vector2.zero()}, food); verify( () => enjoyment.increaseBy(Config.positiveImpactOnEnjoyment), ).called(1); game.update(0); await game.ready(); expect(unicorn.firstChild<StarBurstComponent>(), isNotNull); }); } }); flameTester.test('with the wrong type of food', (game) async { final enjoyment = _MockUnicornPercentage(); final foodCollidingBehavior = FoodCollidingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), unicornComponent: ChildUnicornComponent(), behaviors: [ foodCollidingBehavior, ], enjoyment: enjoyment, )..isLeaving = false; await game.background.ensureAdd(unicorn); final food = _MockFood(); when(() => food.type).thenReturn(FoodType.cake); when(() => food.wasDragged).thenReturn(true); when(() => food.beingDragged).thenReturn(false); when(() => food.isRemoving).thenReturn(false); foodCollidingBehavior.onCollision({Vector2.zero()}, food); verify( () => enjoyment.increaseBy(Config.negativeImpactOnEnjoyment), ).called(1); game.update(0); await game.ready(); expect(unicorn.firstChild<StarBurstComponent>(), isNull); }); }); group('feeding unicorn impacts fullness', () { group('in a positive way', () { for (final stageFullnessResult in { UnicornEvolutionStage.baby: 0.45, UnicornEvolutionStage.child: 0.25, UnicornEvolutionStage.teen: 0.18, UnicornEvolutionStage.adult: 0.25, }.entries) { flameTester.test('for ${stageFullnessResult.key.name}', (game) async { final evolutionStage = stageFullnessResult.key; final fullnessResult = stageFullnessResult.value; final fullness = _MockUnicornPercentage(); final foodCollidingBehavior = FoodCollidingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), unicornComponent: evolutionStage.componentForEvolutionStage(), behaviors: [ foodCollidingBehavior, ], fullness: fullness, ); await game.background.ensureAdd(unicorn); final food = _MockFood(); when(() => food.type).thenReturn(FoodType.cake); when(() => food.wasDragged).thenReturn(true); when(() => food.beingDragged).thenReturn(false); when(() => food.isRemoving).thenReturn(false); foodCollidingBehavior.onCollision({Vector2.zero()}, food); verify(() => fullness.increaseBy(fullnessResult)).called(1); }); } }); }); group('feeding unicorn impacts times fed', () { flameTester.test('summing one up', (game) async { final foodCollidingBehavior = FoodCollidingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), behaviors: [foodCollidingBehavior], ); await game.background.ensureAdd(unicorn); final food = _MockFood(); when(() => food.type).thenReturn(FoodType.cake); when(() => food.wasDragged).thenReturn(true); when(() => food.beingDragged).thenReturn(false); when(() => food.isRemoving).thenReturn(false); expect(unicorn.timesFed, 0); foodCollidingBehavior.onCollision({Vector2.zero()}, food); expect(unicorn.timesFed, 1); }); }); group('feeding unicorn impacts food used', () { flameTester.test('setting it to true', (game) async { final foodCollidingBehavior = FoodCollidingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), behaviors: [foodCollidingBehavior], ); await game.background.ensureAdd(unicorn); final food = _MockFood(); when(() => food.type).thenReturn(FoodType.cake); when(() => food.wasDragged).thenReturn(true); when(() => food.beingDragged).thenReturn(false); when(() => food.isRemoving).thenReturn(false); verifyNever(food.removeFromParent); foodCollidingBehavior.onCollision({Vector2.zero()}, food); verify(food.removeFromParent).called(1); }); }); group('feeding unicorn starts eating animation', () { flameTester.test('by changing state', (game) async { final foodCollidingBehavior = FoodCollidingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), behaviors: [foodCollidingBehavior], ); await game.background.ensureAdd(unicorn); final food = _MockFood(); when(() => food.type).thenReturn(FoodType.cake); when(() => food.wasDragged).thenReturn(true); when(() => food.beingDragged).thenReturn(false); when(() => food.isRemoving).thenReturn(false); expect(unicorn.timesFed, 0); unicorn.setUnicornState(UnicornState.walking); await game.ready(); expect(unicorn.state, UnicornState.walking); expect(unicorn.hasBehavior<WanderBehavior>(), true); foodCollidingBehavior.onCollision({Vector2.zero()}, food); final wanderBehavior = game.descendants().whereType<WanderBehavior>().first; expect(unicorn.state, UnicornState.eating); expect(wanderBehavior.isRemoving, true); }); }); }); }
very_good_ranch/test/game/entities/unicorn/behaviours/food_colliding_behavior_test.dart/0
{'file_path': 'very_good_ranch/test/game/entities/unicorn/behaviours/food_colliding_behavior_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 4528}
import 'package:bloc_test/bloc_test.dart'; import 'package:flame/game.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:ranch_ui/ranch_ui.dart'; import 'package:very_good_ranch/game/game.dart'; import 'package:very_good_ranch/game_menu/game_menu.dart'; import 'package:very_good_ranch/l10n/l10n.dart'; import '../../helpers/helpers.dart'; void main() { late TestGame testGame; setUp(() { testGame = TestGame(); }); group('GameView', () { testWidgets('renders correctly', (tester) async { await tester.pumpApp( Scaffold( body: GameView(game: testGame), ), ); expect(find.byType(GameWidget<TestGame>), findsOneWidget); expect(find.byType(IconButton), findsOneWidget); }); group('settings button', () { testWidgets('should open the settings dialog', (tester) async { final settingsBloc = MockSettingsBloc(); whenListen( settingsBloc, const Stream<SettingsState>.empty(), initialState: const SettingsState(), ); await AppLocalizations.delegate.load(const Locale('en')); await tester.pumpApp( settingsBloc: settingsBloc, Scaffold( body: GameView(game: testGame), ), ); expect(testGame.paused, isFalse); await tester.tap(find.byType(IconButton)); await tester.pump(); expect(testGame.paused, isTrue); expect(find.byType(GameMenuDialog), findsOneWidget); await tester.tap(find.byType(ModalCloseButton)); await tester.pump(); expect(testGame.paused, isFalse); }); }); }); }
very_good_ranch/test/game/widgets/game_view_test.dart/0
{'file_path': 'very_good_ranch/test/game/widgets/game_view_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 736}
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:{{project_name.snakeCase()}}/counter/counter.dart'; import 'package:{{project_name.snakeCase()}}/l10n/l10n.dart'; import 'package:wearable_rotary/wearable_rotary.dart' as wearable_rotary show rotaryEvents; import 'package:wearable_rotary/wearable_rotary.dart' hide rotaryEvents; class CounterPage extends StatelessWidget { const CounterPage({super.key}); @override Widget build(BuildContext context) { return BlocProvider( create: (_) => CounterCubit(), child: CounterView(), ); } } class CounterView extends StatefulWidget { CounterView({ super.key, @visibleForTesting Stream<RotaryEvent>? rotaryEvents, }) : rotaryEvents = rotaryEvents ?? wearable_rotary.rotaryEvents; final Stream<RotaryEvent> rotaryEvents; @override State<CounterView> createState() => _CounterViewState(); } class _CounterViewState extends State<CounterView> { late final StreamSubscription<RotaryEvent> rotarySubscription; @override void initState() { super.initState(); rotarySubscription = widget.rotaryEvents.listen(handleRotaryEvent); } @override void dispose() { rotarySubscription.cancel(); super.dispose(); } void handleRotaryEvent(RotaryEvent event) { final cubit = context.read<CounterCubit>(); if (event.direction == RotaryDirection.clockwise) { cubit.increment(); } else { cubit.decrement(); } } @override Widget build(BuildContext context) { final l10n = context.l10n; return Scaffold( body: SizedBox.expand( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: () => context.read<CounterCubit>().increment(), child: const Icon(Icons.add), ), const SizedBox( height: 10, ), Text(l10n.counterAppBarTitle), const CounterText(), const SizedBox(height: 10), ElevatedButton( onPressed: () => context.read<CounterCubit>().decrement(), child: const Icon(Icons.remove), ), ], ), ), ); } } class CounterText extends StatelessWidget { const CounterText({super.key}); @override Widget build(BuildContext context) { final theme = Theme.of(context); final count = context.select((CounterCubit cubit) => cubit.state); return Text('$count', style: theme.textTheme.displayMedium); } }
very_good_wear_app/brick/__brick__/{{project_name.snakeCase()}}/lib/counter/view/counter_page.dart/0
{'file_path': 'very_good_wear_app/brick/__brick__/{{project_name.snakeCase()}}/lib/counter/view/counter_page.dart', 'repo_id': 'very_good_wear_app', 'token_count': 1052}
name: very_good_wear_app description: A Very Good WearOS Flutter app created by Very Good Ventures. repository: https://github.com/VeryGoodOpenSource/very_good_wear_app version: 0.3.0 environment: mason: ">=0.1.0-dev.50 <0.1.0" vars: project_name: type: string description: The project name default: my_wear_app prompt: What is the project name? org_name: type: string description: The organization name default: com.example prompt: What is the organization name? application_id: type: string description: The application id. If omitted value will be formed by org_name + . + project_name. prompt: What is the application id? description: type: string description: A short project description default: A Very Good Wear OS App prompt: What is the project description?
very_good_wear_app/brick/brick.yaml/0
{'file_path': 'very_good_wear_app/brick/brick.yaml', 'repo_id': 'very_good_wear_app', 'token_count': 276}
import 'package:intl/intl.dart'; import 'dart:convert'; extension StringExtensions on String { /// String get currencyFormat => NumberFormat('###.0#', 'en_US').format(this); } extension NullableStringExtensions on String? { /// String get defaultEmptyString => this ?? ''; String get tobase64 => this == null ? '' : base64.encode(utf8.encode(this!)); }
vigo-interview/lib/src/utils/extensions/string_extensions.dart/0
{'file_path': 'vigo-interview/lib/src/utils/extensions/string_extensions.dart', 'repo_id': 'vigo-interview', 'token_count': 121}
import 'package:rebloc/rebloc.dart'; import 'package:voute/models/user/user.dart'; import 'package:voute/rebloc/blocs/auth.dart'; import 'package:voute/rebloc/blocs/bootstrap.dart'; import 'package:voute/rebloc/blocs/initialize.dart'; import 'package:voute/rebloc/blocs/logger.dart'; import 'package:voute/rebloc/blocs/user.dart'; import 'package:voute/rebloc/states/app.dart'; import 'package:voute/rebloc/states/user.dart'; Store<AppState> reblocStore({UserModel user}) { return Store<AppState>( initialState: AppState.initialState().rebuild( (b) => b..user = UserState.withUser(user).toBuilder(), ), blocs: [ LoggerBloc(), InitializeBloc(), AuthBloc(), BootstrapBloc(), UserBloc(), ], ); }
voute/lib/rebloc/main.dart/0
{'file_path': 'voute/lib/rebloc/main.dart', 'repo_id': 'voute', 'token_count': 321}
import 'package:feather_icons_flutter/feather_icons_flutter.dart'; import 'package:flutter/material.dart'; import 'package:voute/constants/mk_colors.dart'; import 'package:voute/screens/people/_partials/person_item.dart'; import 'package:voute/utils/mk_screen_util.dart'; import 'package:voute/utils/mk_sliver_separator_builder_delegate.dart'; import 'package:voute/widgets/_partials/mk_app_bar_alt.dart'; import 'package:voute/widgets/_partials/mk_icon_button.dart'; class PeoplePage extends StatefulWidget { const PeoplePage({Key key}) : super(key: key); @override _PeoplePageState createState() => _PeoplePageState(); } class _PeoplePageState extends State<PeoplePage> { @override Widget build(BuildContext context) { return CustomScrollView( physics: const BouncingScrollPhysics(), slivers: <Widget>[ MkSliverAppBarAlt( child: MkSearchBarRow( trailing: MkIconButton( icon: FeatherIcons.plus, fillColor: MkColors.dark.shade50, onPressed: () {}, ), ), ), SliverPadding( padding: EdgeInsets.symmetric(horizontal: sw(16), vertical: sh(16)), sliver: SliverList( delegate: MkSliverSeparatorBuilderDelegate( builder: (BuildContext context, int index) { return PersonItem(); }, separatorBuilder: (BuildContext context, int index) { return SizedBox(height: sh(12)); }, childCount: 25, ), ), ), ], ); } }
voute/lib/screens/people/people_page.dart/0
{'file_path': 'voute/lib/screens/people/people_page.dart', 'repo_id': 'voute', 'token_count': 724}
import 'package:colorize_lumberdash/colorize_lumberdash.dart'; import 'package:lumberdash/lumberdash.dart'; import 'package:voute/utils/mk_exceptions.dart'; class MkLogger { static void init(bool isDebug) => putLumberdashToWork(withClients: [ColorizeLumberdash()]); static void w(String reason) => logWarning(reason); static void f(String reason) => logFatal(reason); static void d(String reason) => logMessage(reason); static void e(dynamic reason) => logError(MkException(reason)); }
voute/lib/utils/mk_logger.dart/0
{'file_path': 'voute/lib/utils/mk_logger.dart', 'repo_id': 'voute', 'token_count': 161}
import 'package:flutter/material.dart'; import 'package:voute/widgets/_partials/mk_app_bar.dart'; class PlaceholderView extends StatelessWidget { const PlaceholderView({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold(appBar: MkAppBar(title: Text("Placeholder"))); } }
voute/lib/widgets/_views/placeholder_view.dart/0
{'file_path': 'voute/lib/widgets/_views/placeholder_view.dart', 'repo_id': 'voute', 'token_count': 109}
import 'package:flutter/material.dart'; class OutputWindow extends StatelessWidget { const OutputWindow({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Container( // color: Colors.white, ); } }
vscode_ipad/lib/ui/windows/output.dart/0
{'file_path': 'vscode_ipad/lib/ui/windows/output.dart', 'repo_id': 'vscode_ipad', 'token_count': 92}
import 'dart:math'; import 'package:flutter/material.dart'; class DashedBorderContainer extends StatelessWidget { const DashedBorderContainer({ super.key, this.width, this.height, this.child, this.borderColor, this.borderRadius, this.borderWidth = 1, this.dash = 10, this.gap = 10, }); final double? width; final double? height; final Widget? child; final Color? borderColor; final BorderRadius? borderRadius; final double dash; final double gap; final double borderWidth; @override Widget build(BuildContext context) { return SizedBox.expand( child: CustomPaint( painter: DashedBorderPainter( dashColor: borderColor ?? Theme.of(context).dividerColor, borderRadius: borderRadius ?? BorderRadius.zero, dash: dash, gap: gap, borderWidth: borderWidth, ), child: child, ), ); } } class DashedBorderPainter extends CustomPainter { DashedBorderPainter({ this.dash = 5.0, this.gap = 3.0, this.dashColor = Colors.black, this.borderRadius = BorderRadius.zero, this.borderWidth = 1, }); final double dash; final double gap; final Color dashColor; final BorderRadius borderRadius; final double borderWidth; @override void paint(Canvas canvas, Size size) { final paint = Paint() ..color = dashColor ..strokeWidth = borderWidth ..style = PaintingStyle.stroke; _drawDashedPath( canvas, paint, RRect.fromLTRBAndCorners( 0, 0, size.width, size.height, bottomLeft: borderRadius.bottomLeft, topLeft: borderRadius.topLeft, topRight: borderRadius.topRight, bottomRight: borderRadius.bottomRight, ), ); } void _drawDashedPath(Canvas canvas, Paint paint, RRect rrect) { final path = Path()..addRRect(rrect); final dashLength = dash + gap; for (final metric in path.computeMetrics()) { final totalLength = metric.length; for (var distance = 0.0; distance < totalLength; distance += dashLength) { final start = distance; final double end = min(distance + dash, totalLength); final extractPath = metric.extractPath(start, end); canvas.drawPath(extractPath, paint); } } } @override bool shouldRepaint(CustomPainter oldDelegate) { return false; } }
wallet_app_workshop/lib/core/widgets/dashed_border_container.dart/0
{'file_path': 'wallet_app_workshop/lib/core/widgets/dashed_border_container.dart', 'repo_id': 'wallet_app_workshop', 'token_count': 967}
name: wallet_app_workshop description: Workshop for a minimalistic, animated wallet app with made with Flutter publish_to: 'none' version: 1.0.0+1 environment: sdk: '>=3.1.0 <4.0.0' dependencies: cupertino_icons: ^1.0.2 flutter: sdk: flutter font_awesome_flutter: ^10.5.0 widgetbook: ^3.2.0 dev_dependencies: flutter_launcher_icons: ^0.13.1 flutter_lints: ^2.0.0 flutter_test: sdk: flutter very_good_analysis: ^5.0.0+1 flutter: uses-material-design: true assets: - assets/images/ - assets/icons/ fonts: - family: Raleway fonts: - asset: assets/fonts/Raleway-Regular.ttf - asset: assets/fonts/Raleway-Bold.ttf weight: 700 - asset: assets/fonts/Raleway-Medium.ttf weight: 500 - asset: assets/fonts/Raleway-light.ttf weight: 300 flutter_launcher_icons: android: "launcher_icon" ios: true image_path: "assets/images/app-icon.png" min_sdk_android: 21 # android min sdk min:16, default 21 web: generate: true image_path: "assets/images/app-icon.png" background_color: "#1A1A1A" theme_color: "#1A1A1A" windows: generate: true image_path: "assets/images/app-icon.png" icon_size: 256 macos: generate: true image_path: "assets/images/app-icon.png"
wallet_app_workshop/pubspec.yaml/0
{'file_path': 'wallet_app_workshop/pubspec.yaml', 'repo_id': 'wallet_app_workshop', 'token_count': 586}
import 'package:flutter/material.dart'; import 'package:watch_store/app/models/watch.dart'; class ColorsListWidget extends StatelessWidget { const ColorsListWidget({ Key? key, required this.animationController, required this.watch, }) : super(key: key); final Watch watch; final AnimationController animationController; @override Widget build(BuildContext context) { return ScaleTransition( scale: Tween(begin: 0.5, end: 1.0).animate( CurvedAnimation( parent: animationController, curve: Curves.elasticOut, ), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisSize: MainAxisSize.min, children: watch.colors.map( (watchColor) { final index = watch.colors.indexOf(watchColor); return Expanded( child: Container( padding: const EdgeInsets.symmetric( vertical: 12, horizontal: 8, ), margin: EdgeInsets.only( right: index == watch.colors.length - 1 ? 0 : 8, ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), border: Border.all( color: const Color(0xFF9095A6).withOpacity(0.1), ), color: Colors.white, ), child: Row( children: [ CircleAvatar( radius: 8, backgroundColor: watchColor.color, ), const SizedBox( width: 8, ), Expanded( child: Align( child: Text( watchColor.name, style: TextStyle( fontSize: 12, fontWeight: FontWeight.w500, color: const Color(0xFF9095A6).withOpacity(0.65), ), overflow: TextOverflow.ellipsis, ), ), ), ], ), ), ); }, ).toList(), ), ); } }
watch-store/lib/app/widgets/colors_list_widget.dart/0
{'file_path': 'watch-store/lib/app/widgets/colors_list_widget.dart', 'repo_id': 'watch-store', 'token_count': 1409}
// 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; /// Running Safari Driver which comes installed in every macOS operation system. /// /// The version of driver is the same as the version of the Safari installed /// in the system. class SafariDriverRunner { /// Start Safari Driver installed in the macOS operating system. /// /// If a specific version is requested, it will check the existing system /// version and throw and exception the versions do not match. /// /// If the operating system is not macOS, the method will throw an exception. Future<void> start({String version = 'system'}) async { if (!io.Platform.isMacOS) { throw AssertionError('The operating system must be MacOS: ' '${io.Platform.operatingSystem}'); } final io.Process process = await runDriver(version: version); final int exitCode = await process.exitCode; if (exitCode != 0) { throw Exception('Driver failed with exitcode: $exitCode'); } } /// Safari Driver needs to be enabled before it is used. /// /// The driver will need to get re-enabled after the machine is restarted. /// /// The enabling waits for user input for authentication. void _enableDriver() { io.Process.runSync('/usr/bin/safaridriver', ['--enable']); } /// Compare the version of the installed driver to the requested version. /// /// Throw an exception if they don't match. Future<void> _compareDriverVersion(String version) async { io.Process.run('/usr/bin/safaridriver', ['--version']); final io.ProcessResult versionResult = await io.Process.run('/usr/bin/safaridriver', ['--version']); if (versionResult.exitCode != 0) { throw Exception('Failed to get the safari driver version.'); } // The output generally looks like: Included with Safari 13.0.5 (14608.5.12) final String output = versionResult.stdout as String; final String rest = output.substring(output.indexOf('Safari')); print('INFO: driver version in the system: $rest'); // Version number such as 13.0.5. final String versionAsString = rest.trim().split(' ')[1]; if (versionAsString != version) { throw Exception('System version $versionAsString did not match requested ' 'version $version'); } } /// Run Safari Driver installed in the macOS operating system and return /// the driver Process. /// /// Returns a `Future<Process>` that completes with a /// Process instance when the process has been successfully /// started. That [Process] object can be used to interact with the /// process. If the process cannot be started the returned [Future] /// completes with an exception. /// /// If a specific version is requested, it will check the existing system /// version and throw and exception the versions do not match. Future<io.Process> runDriver({String version = 'system'}) async { _enableDriver(); if (version != 'system') { await _compareDriverVersion(version); print('INFO: Safari Driver will start with version $version on port ' '4444'); } else { // Driver does not have any output. // Printing this one as a info message. print('INFO: Safari Driver will start on port 4444.'); } return io.Process.start('/usr/bin/safaridriver', ['--port=4444']); } }
web_installers/packages/web_drivers/lib/safari_driver_runner.dart/0
{'file_path': 'web_installers/packages/web_drivers/lib/safari_driver_runner.dart', 'repo_id': 'web_installers', 'token_count': 1050}
// ignore_for_file: avoid_equals_and_hash_code_on_mutable_classes /// {@template connection_state} /// The state of a WebSocket connection. /// {@endtemplate} abstract class ConnectionState { /// {@macro connection_state} const ConnectionState(); } /// {@template connecting} /// The WebSocket connection has not yet been established. /// {@endtemplate} class Connecting extends ConnectionState { /// {@macro connecting} const Connecting(); @override int get hashCode => 0; @override bool operator ==(Object other) { return identical(this, other) || other is Connecting; } } /// {@template connected} /// The WebSocket connection is established and communication is possible. /// {@endtemplate} class Connected extends ConnectionState { /// {@macro connected} const Connected(); @override int get hashCode => 1; @override bool operator ==(Object other) { return identical(this, other) || other is Connected; } } /// {@template reconnecting} /// The WebSocket connection was lost /// and is in the process of being re-established. /// {@endtemplate} class Reconnecting extends ConnectionState { /// {@macro reconnecting} const Reconnecting(); @override int get hashCode => 2; @override bool operator ==(Object other) { return identical(this, other) || other is Reconnecting; } } /// {@template reconnected} /// The WebSocket connection was lost and has been re-established. /// {@endtemplate} class Reconnected extends ConnectionState { /// {@macro reconnected} const Reconnected(); @override int get hashCode => 3; @override bool operator ==(Object other) { return identical(this, other) || other is Reconnected; } } /// {@template disconnecting} /// The WebSocket connection is going through the closing handshake, /// or the close() method has been invoked. /// {@endtemplate} class Disconnecting extends ConnectionState { /// {@macro disconnecting} const Disconnecting(); @override int get hashCode => 4; @override bool operator ==(Object other) { return identical(this, other) || other is Disconnecting; } } /// {@template disconnected} /// The WebSocket connection has been closed or could not be established. /// {@endtemplate} class Disconnected extends ConnectionState { /// {@macro disconnected} const Disconnected({this.code, this.reason, this.error, this.stackTrace}); /// The error responsible for the disconnection. final Object? error; /// The stack trace responsible for the disconnection. final StackTrace? stackTrace; /// The WebSocket connection close code. final int? code; /// The WebSocket connection close reason. final String? reason; @override int get hashCode => Object.hashAll([code, reason]); @override bool operator ==(Object other) { return identical(this, other) || other is Disconnected && code == other.code && reason == other.reason && other.error == error && other.stackTrace == stackTrace; } }
web_socket_client/lib/src/connection_state.dart/0
{'file_path': 'web_socket_client/lib/src/connection_state.dart', 'repo_id': 'web_socket_client', 'token_count': 911}
targets: $default: sources: include: - examples/** # Some default includes that aren't really used here but will prevent # false-negative warnings: - $package$ - lib/$lib$ exclude: - '**/.*/**' - '**/android/**' - '**/ios/**' - '**/linux/**' - '**/macos/**' - '**/windows/**' - '**/build/**' - '**/node_modules/**' - '**/*.jar' - '**/codelab_rebuild.yaml' builders: code_excerpter|code_excerpter: enabled: true
website/build.excerpt.yaml/0
{'file_path': 'website/build.excerpt.yaml', 'repo_id': 'website', 'token_count': 298}
name: staggered_pic_selection publish_to: none description: A more complex staggered animation example. 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/pic1.jpg - images/pic2.jpg - images/pic3.jpg - images/pic4.jpg - images/pic5.jpg - images/pic6.jpg - images/pic7.jpg - images/pic8.jpg - images/pic9.jpg - images/pic10.jpg - images/pic11.jpg - images/pic12.jpg - images/pic13.jpg - images/pic14.jpg - images/pic15.jpg - images/pic16.jpg - images/pic17.jpg - images/pic18.jpg - images/pic19.jpg - images/pic20.jpg - images/pic21.jpg - images/pic22.jpg - images/pic23.jpg - images/pic24.jpg - images/pic25.jpg - images/pic26.jpg - images/pic27.jpg - images/pic28.jpg - images/pic29.jpg - images/pic30.jpg
website/examples/_animation/staggered_pic_selection/pubspec.yaml/0
{'file_path': 'website/examples/_animation/staggered_pic_selection/pubspec.yaml', 'repo_id': 'website', 'token_count': 448}
# Take our settings from the example_utils analysis_options.yaml file. # If necessary for a particular example, this file can also include # overrides for individual lints. include: package:example_utils/analysis.yaml analyzer: errors: # Ignored since ignore_for_files can't be hidden in diff excerpts yet missing_required_argument: ignore
website/examples/animation/implicit/analysis_options.yaml/0
{'file_path': 'website/examples/animation/implicit/analysis_options.yaml', 'repo_id': 'website', 'token_count': 96}
import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp(home: PhysicsCardDragDemo())); } class PhysicsCardDragDemo extends StatelessWidget { const PhysicsCardDragDemo({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: const DraggableCard( child: FlutterLogo( size: 128, ), ), ); } } class DraggableCard extends StatefulWidget { const DraggableCard({required this.child, super.key}); final Widget child; @override State<DraggableCard> createState() => _DraggableCardState(); } // #docregion alignment class _DraggableCardState extends State<DraggableCard> with SingleTickerProviderStateMixin { late AnimationController _controller; // #enddocregion alignment @override void initState() { super.initState(); _controller = AnimationController(vsync: this, duration: const Duration(seconds: 1)); } @override void dispose() { _controller.dispose(); super.dispose(); } // #docregion build @override Widget build(BuildContext context) { return Align( child: Card( child: widget.child, ), ); } // #enddocregion build }
website/examples/cookbook/animation/physics_simulation/lib/step1.dart/0
{'file_path': 'website/examples/cookbook/animation/physics_simulation/lib/step1.dart', 'repo_id': 'website', 'token_count': 455}
// ignore_for_file: unused_element, prefer_const_literals_to_create_immutables import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @immutable class ButtonShapeWidget extends StatelessWidget { const ButtonShapeWidget({ super.key, required this.isDownloading, required this.isDownloaded, required this.isFetching, required this.transitionDuration, }); final bool isDownloading; final bool isDownloaded; final bool isFetching; final Duration transitionDuration; @override Widget build(BuildContext context) { var shape = const ShapeDecoration( shape: StadiumBorder(), color: CupertinoColors.lightBackgroundGray, ); if (isDownloading || isFetching) { shape = ShapeDecoration( shape: const CircleBorder(), color: Colors.white.withOpacity(0), ); } return AnimatedContainer( duration: transitionDuration, curve: Curves.ease, width: double.infinity, decoration: shape, child: Padding( padding: const EdgeInsets.symmetric(vertical: 6), child: AnimatedOpacity( duration: transitionDuration, opacity: isDownloading || isFetching ? 0.0 : 1.0, curve: Curves.ease, child: Text( isDownloaded ? 'OPEN' : 'GET', textAlign: TextAlign.center, style: Theme.of(context).textTheme.labelLarge?.copyWith( fontWeight: FontWeight.bold, color: CupertinoColors.activeBlue, ), ), ), ), ); } } @immutable class ProgressIndicatorWidget extends StatelessWidget { const ProgressIndicatorWidget({ super.key, required this.downloadProgress, required this.isDownloading, required this.isFetching, }); final double downloadProgress; final bool isDownloading; final bool isFetching; @override Widget build(BuildContext context) { return AspectRatio( aspectRatio: 1, child: TweenAnimationBuilder<double>( tween: Tween(begin: 0, end: downloadProgress), duration: const Duration(milliseconds: 200), builder: (context, progress, child) { return CircularProgressIndicator( backgroundColor: isDownloading ? CupertinoColors.lightBackgroundGray : Colors.white.withOpacity(0), valueColor: AlwaysStoppedAnimation(isFetching ? CupertinoColors.lightBackgroundGray : CupertinoColors.activeBlue), strokeWidth: 2, value: isFetching ? null : progress, ); }, ), ); } } enum DownloadStatus { notDownloaded, fetchingDownload, downloading, downloaded, } // #docregion TapCallbacks @immutable class DownloadButton extends StatelessWidget { const DownloadButton({ super.key, required this.status, this.downloadProgress = 0, required this.onDownload, required this.onCancel, required this.onOpen, this.transitionDuration = const Duration(milliseconds: 500), }); final DownloadStatus status; final double downloadProgress; final VoidCallback onDownload; final VoidCallback onCancel; final VoidCallback onOpen; final Duration transitionDuration; bool get _isDownloading => status == DownloadStatus.downloading; bool get _isFetching => status == DownloadStatus.fetchingDownload; bool get _isDownloaded => status == DownloadStatus.downloaded; void _onPressed() { switch (status) { case DownloadStatus.notDownloaded: onDownload(); case DownloadStatus.fetchingDownload: // do nothing. break; case DownloadStatus.downloading: onCancel(); case DownloadStatus.downloaded: onOpen(); } } @override Widget build(BuildContext context) { return GestureDetector( onTap: _onPressed, child: const Stack( children: [ /* ButtonShapeWidget and progress indicator */ ], ), ); } } // #enddocregion TapCallbacks
website/examples/cookbook/effects/download_button/lib/button_taps.dart/0
{'file_path': 'website/examples/cookbook/effects/download_button/lib/button_taps.dart', 'repo_id': 'website', 'token_count': 1602}
import 'package:flutter/material.dart'; class SetupFlow extends StatefulWidget { const SetupFlow({ super.key, required this.setupPageRoute, }); final String setupPageRoute; @override State<SetupFlow> createState() => SetupFlowState(); } class SetupFlowState extends State<SetupFlow> { // #docregion SetupFlow2 @override Widget build(BuildContext context) { return Scaffold( appBar: _buildFlowAppBar(), body: const SizedBox(), ); } PreferredSizeWidget _buildFlowAppBar() { return AppBar( title: const Text('Bulb Setup'), ); } // #enddocregion SetupFlow2 }
website/examples/cookbook/effects/nested_nav/lib/setupflow2.dart/0
{'file_path': 'website/examples/cookbook/effects/nested_nav/lib/setupflow2.dart', 'repo_id': 'website', 'token_count': 219}
import 'package:flutter/material.dart'; @immutable class FilterSelector extends StatefulWidget { const FilterSelector({ super.key, required this.filters, required this.onFilterChanged, this.padding = const EdgeInsets.symmetric(vertical: 24), }); final List<Color> filters; final void Function(Color selectedColor) onFilterChanged; final EdgeInsets padding; @override State<FilterSelector> createState() => _FilterSelectorState(); } class _FilterSelectorState extends State<FilterSelector> { static const _filtersPerScreen = 5; static const _viewportFractionPerItem = 1.0 / _filtersPerScreen; late final PageController _controller; Color itemColor(int index) => widget.filters[index % widget.filters.length]; @override void initState() { super.initState(); _controller = PageController( viewportFraction: _viewportFractionPerItem, ); _controller.addListener(_onPageChanged); } void _onPageChanged() { final page = (_controller.page ?? 0).round(); widget.onFilterChanged(widget.filters[page]); } @override void dispose() { _controller.dispose(); super.dispose(); } // #docregion BuildCarousel Widget _buildCarousel(double itemSize) { return Container( height: itemSize, margin: widget.padding, child: PageView.builder( controller: _controller, itemCount: widget.filters.length, itemBuilder: (context, index) { return Center( child: AnimatedBuilder( animation: _controller, builder: (context, child) { return FilterItem( color: itemColor(index), onFilterSelected: () => {}, ); }, ), ); }, ), ); } // #enddocregion BuildCarousel @override Widget build(BuildContext context) { _buildCarousel(5); // Makes sure _buildCarousel is used return Container(); } } @immutable class FilterItem extends StatelessWidget { const FilterItem({ super.key, required this.color, this.onFilterSelected, }); final Color color; final VoidCallback? onFilterSelected; @override Widget build(BuildContext context) { return GestureDetector( onTap: onFilterSelected, child: AspectRatio( aspectRatio: 1.0, child: Padding( padding: const EdgeInsets.all(8), child: ClipOval( child: Image.network( 'https://docs.flutter.dev/cookbook/img-files' '/effects/instagram-buttons/millennial-texture.jpg', color: color.withOpacity(0.5), colorBlendMode: BlendMode.hardLight, ), ), ), ), ); } }
website/examples/cookbook/effects/photo_filter_carousel/lib/excerpt6.dart/0
{'file_path': 'website/examples/cookbook/effects/photo_filter_carousel/lib/excerpt6.dart', 'repo_id': 'website', 'token_count': 1140}
// ignore_for_file: unused_field import 'package:flutter/material.dart'; class Menu extends StatefulWidget { const Menu({super.key}); @override State<Menu> createState() => _MenuState(); } // #docregion step3 class _MenuState extends State<Menu> with SingleTickerProviderStateMixin { final List<Interval> _itemSlideIntervals = []; late Interval _buttonInterval; @override void initState() { super.initState(); _createAnimationIntervals(); _staggeredController = AnimationController( vsync: this, duration: _animationDuration, ); } void _createAnimationIntervals() { for (var i = 0; i < _menuTitles.length; ++i) { final startTime = _initialDelayTime + (_staggerTime * i); final endTime = startTime + _itemSlideTime; _itemSlideIntervals.add( Interval( startTime.inMilliseconds / _animationDuration.inMilliseconds, endTime.inMilliseconds / _animationDuration.inMilliseconds, ), ); } final buttonStartTime = Duration(milliseconds: (_menuTitles.length * 50)) + _buttonDelayTime; final buttonEndTime = buttonStartTime + _buttonTime; _buttonInterval = Interval( buttonStartTime.inMilliseconds / _animationDuration.inMilliseconds, buttonEndTime.inMilliseconds / _animationDuration.inMilliseconds, ); } //code-excerpt-close-bracket // #enddocregion step3 @override Widget build(BuildContext context) { return Container(); } late AnimationController _staggeredController; static const _initialDelayTime = Duration(milliseconds: 50); static const _itemSlideTime = Duration(milliseconds: 250); static const _staggerTime = Duration(milliseconds: 50); static const _buttonDelayTime = Duration(milliseconds: 150); static const _buttonTime = Duration(milliseconds: 500); final _animationDuration = _initialDelayTime + (_staggerTime * _menuTitles.length) + _buttonDelayTime + _buttonTime; static const _menuTitles = [ 'Declarative style', 'Premade widgets', 'Stateful hot reload', 'Native performance', 'Great community', ]; }
website/examples/cookbook/effects/staggered_menu_animation/lib/step3.dart/0
{'file_path': 'website/examples/cookbook/effects/staggered_menu_animation/lib/step3.dart', 'repo_id': 'website', 'token_count': 756}
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } // MyApp is a StatefulWidget. This allows updating the state of the // widget when an item is removed. class MyApp extends StatefulWidget { const MyApp({super.key}); @override MyAppState createState() { return MyAppState(); } } class MyAppState extends State<MyApp> { // #docregion Items final items = List<String>.generate(20, (i) => 'Item ${i + 1}'); // #enddocregion Items @override Widget build(BuildContext context) { const title = 'Dismissing Items'; return MaterialApp( title: title, theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: Scaffold( appBar: AppBar( title: const Text(title), ), body: ListView.builder( itemCount: items.length, // #docregion Dismissible itemBuilder: (context, index) { final item = items[index]; return Dismissible( // Each Dismissible must contain a Key. Keys allow Flutter to // uniquely identify widgets. key: Key(item), // Provide a function that tells the app // what to do after an item has been swiped away. onDismissed: (direction) { // Remove the item from the data source. setState(() { items.removeAt(index); }); // Then show a snackbar. ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text('$item dismissed'))); }, // Show a red background as the item is swiped away. background: Container(color: Colors.red), child: ListTile( title: Text(item), ), ); }, // #enddocregion Dismissible ), ), ); } }
website/examples/cookbook/gestures/dismissible/lib/main.dart/0
{'file_path': 'website/examples/cookbook/gestures/dismissible/lib/main.dart', 'repo_id': 'website', 'token_count': 917}
import 'package:flutter/material.dart'; import 'package:transparent_image/transparent_image.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const title = 'Fade in images'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar( title: const Text(title), ), body: Stack( children: <Widget>[ const Center(child: CircularProgressIndicator()), Center( // #docregion MemoryNetwork child: FadeInImage.memoryNetwork( placeholder: kTransparentImage, image: 'https://picsum.photos/250?image=9', ), // #enddocregion MemoryNetwork ), ], ), ), ); } }
website/examples/cookbook/images/fading_in_images/lib/memory_main.dart/0
{'file_path': 'website/examples/cookbook/images/fading_in_images/lib/memory_main.dart', 'repo_id': 'website', 'token_count': 418}
name: error_reporting description: error reporting environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter sentry_flutter: ^7.0.0 dev_dependencies: example_utils: path: ../../../example_utils flutter_test: sdk: flutter flutter: uses-material-design: true
website/examples/cookbook/maintenance/error_reporting/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/maintenance/error_reporting/pubspec.yaml', 'repo_id': 'website', 'token_count': 115}
import 'package:flutter/material.dart'; class FirstRoute extends StatelessWidget { const FirstRoute({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('First Route'), ), body: Center( child: ElevatedButton( child: const Text('Open route'), // #docregion FirstRouteOnPressed // Within the `FirstRoute` widget onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const SecondRoute()), ); } // #enddocregion FirstRouteOnPressed ), ), ); } } class SecondRoute extends StatelessWidget { const SecondRoute({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Second Route'), ), body: Center( child: ElevatedButton( // #docregion SecondRouteOnPressed // Within the SecondRoute widget onPressed: () { Navigator.pop(context); } // #enddocregion SecondRouteOnPressed , child: const Text('Go back!'), ), ), ); } }
website/examples/cookbook/navigation/navigation_basics/lib/main_step2.dart/0
{'file_path': 'website/examples/cookbook/navigation/navigation_basics/lib/main_step2.dart', 'repo_id': 'website', 'token_count': 605}
import 'dart:async'; import 'package:http/http.dart' as http; // #docregion fetchPhotos Future<http.Response> fetchPhotos(http.Client client) async { return client.get(Uri.parse('https://jsonplaceholder.typicode.com/photos')); } // #enddocregion fetchPhotos
website/examples/cookbook/networking/background_parsing/lib/main_step2.dart/0
{'file_path': 'website/examples/cookbook/networking/background_parsing/lib/main_step2.dart', 'repo_id': 'website', 'token_count': 87}
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; // #docregion Http import 'package:http/http.dart' as http; // #enddocregion Http // #docregion fetchAlbum Future<Album> fetchAlbum() async { final response = await http.get( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), ); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to load album'); } } // #enddocregion fetchAlbum // #docregion updateAlbum Future<Album> updateAlbum(String title) async { final response = await http.put( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to update album.'); } } // #enddocregion updateAlbum // #docregion Album class Album { final int id; final String title; const Album({required this.id, required this.title}); factory Album.fromJson(Map<String, dynamic> json) { return switch (json) { { 'id': int id, 'title': String title, } => Album( id: id, title: title, ), _ => throw const FormatException('Failed to load album.'), }; } } // #enddocregion Album void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() { return _MyAppState(); } } class _MyAppState extends State<MyApp> { final TextEditingController _controller = TextEditingController(); late Future<Album> _futureAlbum; @override void initState() { super.initState(); _futureAlbum = fetchAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Update Data Example', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: Scaffold( appBar: AppBar( title: const Text('Update Data Example'), ), body: Container( alignment: Alignment.center, padding: const EdgeInsets.all(8), child: FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(snapshot.data!.title), TextField( controller: _controller, decoration: const InputDecoration( hintText: 'Enter Title', ), ), ElevatedButton( onPressed: () { setState(() { _futureAlbum = updateAlbum(_controller.text); }); }, child: const Text('Update Data'), ), ], ); } else if (snapshot.hasError) { return Text('${snapshot.error}'); } } return const CircularProgressIndicator(); }, ), ), ), ); } }
website/examples/cookbook/networking/update_data/lib/main.dart/0
{'file_path': 'website/examples/cookbook/networking/update_data/lib/main.dart', 'repo_id': 'website', 'token_count': 1850}
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; void main() => runApp(const VideoPlayerApp()); class VideoPlayerApp extends StatelessWidget { const VideoPlayerApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Video Player Demo', home: VideoPlayerScreen(), ); } } class VideoPlayerScreen extends StatefulWidget { const VideoPlayerScreen({super.key}); @override State<VideoPlayerScreen> createState() => _VideoPlayerScreenState(); } class _VideoPlayerScreenState extends State<VideoPlayerScreen> { late VideoPlayerController _controller; late Future<void> _initializeVideoPlayerFuture; @override void initState() { super.initState(); // Create and store the VideoPlayerController. The VideoPlayerController // offers several different constructors to play videos from assets, files, // or the internet. _controller = VideoPlayerController.networkUrl( Uri.parse( 'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4', ), ); // Initialize the controller and store the Future for later use. _initializeVideoPlayerFuture = _controller.initialize(); // Use the controller to loop the video. _controller.setLooping(true); } @override void dispose() { // Ensure disposing of the VideoPlayerController to free up resources. _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Butterfly Video'), ), // #docregion FutureBuilder // Use a FutureBuilder to display a loading spinner while waiting for the // VideoPlayerController to finish initializing. body: FutureBuilder( future: _initializeVideoPlayerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { // If the VideoPlayerController has finished initialization, use // the data it provides to limit the aspect ratio of the video. return AspectRatio( aspectRatio: _controller.value.aspectRatio, // Use the VideoPlayer widget to display the video. child: VideoPlayer(_controller), ); } else { // If the VideoPlayerController is still initializing, show a // loading spinner. return const Center( child: CircularProgressIndicator(), ); } }, ), // #enddocregion FutureBuilder // #docregion FAB floatingActionButton: FloatingActionButton( onPressed: () { // Wrap the play or pause in a call to `setState`. This ensures the // correct icon is shown. setState(() { // If the video is playing, pause it. if (_controller.value.isPlaying) { _controller.pause(); } else { // If the video is paused, play it. _controller.play(); } }); }, // Display the correct icon depending on the state of the player. child: Icon( _controller.value.isPlaying ? Icons.pause : Icons.play_arrow, ), ), // #enddocregion FAB ); } }
website/examples/cookbook/plugins/play_video/lib/main.dart/0
{'file_path': 'website/examples/cookbook/plugins/play_video/lib/main.dart', 'repo_id': 'website', 'token_count': 1305}
name: counter_app description: Flutter project for unit testing introduction. publish_to: none version: 1.0.0+1 environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.6 test: ^1.24.6 dev_dependencies: example_utils: path: ../../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/testing/unit/counter_app/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/testing/unit/counter_app/pubspec.yaml', 'repo_id': 'website', 'token_count': 134}
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; // #docregion main void main() { testWidgets('MyWidget has a title and message', (tester) async { await tester.pumpWidget(const MyWidget(title: 'T', message: 'M')); final titleFinder = find.text('T'); final messageFinder = find.text('M'); // Use the `findsOneWidget` matcher provided by flutter_test to verify // that the Text widgets appear exactly once in the widget tree. expect(titleFinder, findsOneWidget); expect(messageFinder, findsOneWidget); }); } // #enddocregion main class MyWidget extends StatelessWidget { const MyWidget({ super.key, required this.title, required this.message, }); final String title; final String message; @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', home: Scaffold( appBar: AppBar( title: Text(title), ), body: Center( child: Text(message), ), ), ); } }
website/examples/cookbook/testing/widget/introduction/test/main_step6_test.dart/0
{'file_path': 'website/examples/cookbook/testing/widget/introduction/test/main_step6_test.dart', 'repo_id': 'website', 'token_count': 400}
// Copyright 2021 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:isolate'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Isolates demo', home: Scaffold( appBar: AppBar( title: const Text('Isolates demo'), ), body: Center( child: ElevatedButton( onPressed: () { getPhotos(); }, child: Text('Fetch photos'), ), ), ), ); } } // #docregion isolate-run // Produces a list of 211,640 photo objects. // (The JSON file is ~20MB.) Future<List<Photo>> getPhotos() async { final String jsonString = await rootBundle.loadString('assets/photos.json'); final List<Photo> photos = await Isolate.run<List<Photo>>(() { final List<Object?> photoData = jsonDecode(jsonString) as List<Object?>; return photoData.cast<Map<String, Object?>>().map(Photo.fromJson).toList(); }); return photos; } // #enddocregion isolate-run class Photo { final int albumId; final int id; final String title; final String thumbnailUrl; Photo({ required this.albumId, required this.id, required this.title, required this.thumbnailUrl, }); factory Photo.fromJson(Map<String, dynamic> data) { return Photo( albumId: data['albumId'] as int, id: data['id'] as int, title: data['title'] as String, thumbnailUrl: data['thumbnailUrl'] as String, ); } }
website/examples/development/concurrency/isolates/lib/main.dart/0
{'file_path': 'website/examples/development/concurrency/isolates/lib/main.dart', 'repo_id': 'website', 'token_count': 686}
// #docregion DynamicLibrary import 'dart:ffi'; // For FFI import 'dart:io'; // For Platform.isX final DynamicLibrary nativeAddLib = Platform.isAndroid ? DynamicLibrary.open('libnative_add.so') : DynamicLibrary.process(); // #enddocregion DynamicLibrary // #docregion NativeAdd final int Function(int x, int y) nativeAdd = nativeAddLib .lookup<NativeFunction<Int32 Function(Int32, Int32)>>('native_add') .asFunction(); // #enddocregion NativeAdd
website/examples/development/platform_integration/lib/c_interop.dart/0
{'file_path': 'website/examples/development/platform_integration/lib/c_interop.dart', 'repo_id': 'website', 'token_count': 150}
// ignore_for_file: avoid_print, prefer_const_declarations, prefer_const_constructors // #docregion Build import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return GestureDetector(onTap: () => print('tapped')); } } // #enddocregion Build // #docregion Enum enum Color { red, green, blue, } // #enddocregion Enum // #docregion Class class A<T> { T? i; } // #enddocregion Class // #docregion SampleTable final sampleTable = [ Table( children: const [ TableRow( children: [Text('T1')], ) ], ), Table( children: const [ TableRow( children: [Text('T2')], ) ], ), Table( children: const [ TableRow( children: [Text('T3')], ) ], ), Table( children: const [ TableRow( children: [Text('T4')], ) ], ), ]; // #enddocregion SampleTable // #docregion Const const foo = 1; final bar = foo; void onClick() { print(foo); print(bar); } // #enddocregion Const
website/examples/development/tools/lib/hot-reload/before.dart/0
{'file_path': 'website/examples/development/tools/lib/hot-reload/before.dart', 'repo_id': 'website', 'token_count': 475}
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; void main() { runApp(const SampleApp()); } // #docregion ToggleWidget 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> { // Default value for toggle. bool toggle = true; void _toggle() { setState(() { toggle = !toggle; }); } Widget _getToggleChild() { if (toggle) { return const Text('Toggle One'); } return CupertinoButton( onPressed: () {}, child: const Text('Toggle Two'), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Sample App'), ), body: Center( child: _getToggleChild(), ), floatingActionButton: FloatingActionButton( onPressed: _toggle, tooltip: 'Update Text', child: const Icon(Icons.update), ), ); } } // #enddocregion ToggleWidget class MyWidget extends StatelessWidget { const MyWidget({super.key}); // #docregion SimpleWidget @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: Center( child: CupertinoButton( onPressed: () {}, padding: const EdgeInsets.only(left: 10, right: 10), child: const Text('Hello'), ), ), ); } // #enddocregion SimpleWidget } class RowExample extends StatelessWidget { const RowExample({super.key}); // #docregion Row @override Widget build(BuildContext context) { return const Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Row One'), Text('Row Two'), Text('Row Three'), Text('Row Four'), ], ); } // #enddocregion Row } class ColumnExample extends StatelessWidget { const ColumnExample({super.key}); // #docregion Column @override Widget build(BuildContext context) { return const Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Column One'), Text('Column Two'), Text('Column Three'), Text('Column Four'), ], ); } // #enddocregion Column } class ListViewExample extends StatelessWidget { const ListViewExample({super.key}); // #docregion ListView @override Widget build(BuildContext context) { return ListView( children: const <Widget>[ Text('Row One'), Text('Row Two'), Text('Row Three'), Text('Row Four'), ], ); } // #enddocregion ListView }
website/examples/get-started/flutter-for/ios_devs/lib/layout.dart/0
{'file_path': 'website/examples/get-started/flutter-for/ios_devs/lib/layout.dart', 'repo_id': 'website', 'token_count': 1177}
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { double turns = 0; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: // #docregion AnimatedButton AnimatedRotation( duration: const Duration(seconds: 1), turns: turns, curve: Curves.easeIn, child: TextButton( onPressed: () { setState(() { turns += .125; }); }, child: const Text('Tap me!')), ), // #enddocregion AnimatedButton ), ); } }
website/examples/get-started/flutter-for/ios_devs/lib/simple_animation.dart/0
{'file_path': 'website/examples/get-started/flutter-for/ios_devs/lib/simple_animation.dart', 'repo_id': 'website', 'token_count': 487}