### Server Side Dart Examples Source: https://docs.flutter.dev/reference/learning-resources This quickstart provides examples of running Dart code on the server, showcasing server-side capabilities. ```dart import 'package:shelf/shelf.dart' as shelf; import 'package:shelf_router/shelf_router.dart'; Future main() async { final app = Router() ..get('/', (shelf.Request request) => shelf.Response.ok('Hello, World!')) ..get('/about', (shelf.Request request) => shelf.Response.ok('About Page')); await shelf.serve(app.handler, 'localhost', 8080); print('Serving at http://localhost:8080'); } ``` -------------------------------- ### Isolates Best Practices Example Source: https://docs.flutter.dev/reference/learning-resources This quickstart provides a sample application that demonstrates best practices for using isolates in Dart for concurrency. ```dart Isolate.spawn( myIsolateFunction, message, ); ``` -------------------------------- ### Package Constraint Solver Best Practices Source: https://docs.flutter.dev/reference/learning-resources This quickstart demonstrates best practices for publishing packages on pub.dev, focusing on the package constraint solver. ```dart environment: sdk: ">=3.0.0 <4.0.0" ``` -------------------------------- ### Counter App with Provider State Management Source: https://docs.flutter.dev/reference/learning-resources This quickstart demonstrates the starter Flutter application modified to use the Provider package for state management. ```dart ChangeNotifierProvider( create: (context) => Counter(), child: const CounterWidget(), ) ``` -------------------------------- ### Shopping App with Provider State Management Source: https://docs.flutter.dev/reference/learning-resources This quickstart presents a sample Flutter shopping application showcasing a state management approach using the Provider package. ```dart ChangeNotifierProvider( create: (_) => CartModel(), child: const ShoppingApp(), ); ``` -------------------------------- ### Desktop UI Features in Material and FluentUI Source: https://docs.flutter.dev/reference/learning-resources This quickstart demonstrates desktop-specific UI features available in both Material Design and FluentUI design systems within Flutter. ```dart MaterialDesktopStyle( child: Scaffold( // ... ), ) ``` -------------------------------- ### FFI: Call C Libraries from Dart Source: https://docs.flutter.dev/reference/learning-resources A series of simple examples demonstrating how to call C libraries from Dart using the Foreign Function Interface (FFI). ```dart import 'dart:ffi'; final DynamicLibrary nativeLib = Platform.isAndroid ? DynamicLibrary.open('libmy_native_lib.so') : DynamicLibrary.process(); final int Function(int, int) add = nativeLib .lookup>('add') .asFunction(); ``` -------------------------------- ### Isolates (in a CLI) for Concurrency Source: https://docs.flutter.dev/reference/learning-resources Command line application examples demonstrating how to work with concurrency in Dart using isolates. ```dart import 'dart:isolate'; void main() async { ReceivePort receivePort = ReceivePort(); await Isolate.spawn(isolateEntry, receivePort.sendPort); receivePort.listen((message) { print('Received: $message'); }); } void isolateEntry(SendPort sendPort) { sendPort.send('Hello from isolate!'); } ``` -------------------------------- ### Background Isolate Channels for Long-Lived Isolates Source: https://docs.flutter.dev/reference/learning-resources This quickstart demonstrates how to use long-lived isolates, often referred to as background isolates, and manage communication channels with them. ```dart ReceivePort _port = ReceivePort(); static void callback() { // ... isolate logic ... } void startBackgroundIsolate() async { await Isolate.spawn(callback, _port.sendPort, paused: true); _port.first.then((dynamic data) { // Handle initial message from isolate }); // ... other communication setup ... } ``` -------------------------------- ### Build a Form with Validation Source: https://docs.flutter.dev/reference/learning-resources This recipe guides you through the process of creating a form in Flutter and implementing input validation. ```dart final _formKey = GlobalKey(); Form( key: _formKey, child: Column( children: [ TextFormField( validator: (value) { if (value == null || value.isEmpty) { return 'Please enter some text'; } return null; }, ), // ... ], ), ) ``` -------------------------------- ### Flutter Form App Example Source: https://docs.flutter.dev/reference/learning-resources A sample application demonstrating various types of forms and best practices for form handling in Flutter. Includes input validation and state management. ```dart import 'package:flutter/material.dart'; class MyForm extends StatefulWidget { const MyForm({super.key}); @override State createState() => _MyFormState(); } class _MyFormState extends State { final _formKey = GlobalKey(); @override Widget build(BuildContext context) { return Form( key: _formKey, child: Column( children: [ TextFormField( validator: (value) { if (value == null || value.isEmpty) { return 'Please enter some text'; } return null; }, ), Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: ElevatedButton( onPressed: () { if (_formKey.currentState!.validate()) { // Process data ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Processing Data')), ); } }, child: const Text('Submit'), ), ) ], ), ); } } ``` -------------------------------- ### Desktop Calculator Sample in Flutter Source: https://docs.flutter.dev/reference/learning-resources A simple calculator sample designed to demonstrate a basic starting point for a desktop Flutter application. Focuses on UI layout and basic arithmetic operations. ```dart import 'package:flutter/material.dart'; class CalculatorScreen extends StatefulWidget { const CalculatorScreen({super.key}); @override State createState() => _CalculatorScreenState(); } class _CalculatorScreenState extends State { String _output = '0'; void _onPressed(String buttonText) { // Calculator logic here setState(() { _output = buttonText; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Desktop Calculator')), body: Column( children: [ Expanded(child: Center(child: Text(_output, style: TextStyle(fontSize: 48)))), // Button grid would go here ], ), ); } } ``` -------------------------------- ### Use the Device Camera in Flutter Source: https://docs.flutter.dev/reference/learning-resources Provides a basic example of how to access and use a device's camera within a Flutter application. This typically requires camera plugin integration. ```dart import 'package:camera/camera.dart'; // Placeholder for camera usage Future takePicture() async { // Ensure camera is initialized and available // final cameras = await availableCameras(); // final firstCamera = cameras.first; // ... camera initialization and capture logic ... print('Camera function called'); } ``` -------------------------------- ### Code Sharing Between Flutter Client and Dart Server Source: https://docs.flutter.dev/reference/learning-resources This quickstart demonstrates how to share business logic between a Flutter client and a Dart server using the `package:shelf` library. ```dart import 'package:shelf/shelf.dart' as shelf; // Shared logic function String getGreeting(String name) => 'Hello, $name!'; // Server handler Future handler(shelf.Request request) async { final name = request.url.queryParameters['name'] ?? 'World'; return shelf.Response.ok(getGreeting(name)); } ``` -------------------------------- ### AI Todo List with Gemini API in Flutter Source: https://docs.flutter.dev/reference/learning-resources A developer sample written in Flutter demonstrating how to interact with a to-do list in natural language using the Gemini API. Requires setup of the Gemini API. ```dart import 'package:flutter/material.dart'; // Assume necessary imports for Gemini API and state management class AiTodoList extends StatefulWidget { const AiTodoList({super.key}); @override State createState() => _AiTodoListState(); } class _AiTodoListState extends State { final TextEditingController _controller = TextEditingController(); List _todos = []; Future _addTodoFromAi(String text) async { // Call Gemini API to process text and add to _todos print('Adding todo from AI: $text'); setState(() { _todos.add(text); }); _controller.clear(); } @override Widget build(BuildContext context) { return Column( children: [ TextField( controller: _controller, decoration: const InputDecoration(hintText: 'Enter task or ask AI'), onSubmitted: _addTodoFromAi, // Or use a button ), Expanded( child: ListView.builder( itemCount: _todos.length, itemBuilder: (context, index) => ListTile(title: Text(_todos[index])), ), ) ], ); } } ``` -------------------------------- ### Web Element Embedding in index.html Source: https://docs.flutter.dev/reference/learning-resources This quickstart modifies the index.html file of a Flutter app to launch within a custom hostElement, demonstrating basic embedding. ```html
``` -------------------------------- ### Angular App with Flutter Element Embedding Source: https://docs.flutter.dev/reference/learning-resources This quickstart features a simple Angular application that replicates element embedding using a Flutter component. ```typescript import { Component, ViewEncapsulation } from '@angular/core'; import '@angular/elements'; @Component({ selector: 'app-root', template: '', encapsulation: ViewEncapsulation.None, }) export class AppComponent {} ``` -------------------------------- ### Add Home Screen Widget to Flutter App (iOS) Source: https://docs.flutter.dev/reference/learning-resources This codelab guides you through adding a Home Screen widget to your Flutter app, applicable to iOS home screens, lock screens, or the today view. ```swift func getTimeline(for configuration: INIntent, with completion: @escaping (INTimelime) -> Void) { ``` -------------------------------- ### Add-to-App Recommended Approaches Source: https://docs.flutter.dev/reference/learning-resources This demo outlines recommended approaches for integrating Flutter into existing native applications. ```dart FlutterEngine engine = FlutterEngine(withEntrypoint: "my_entrypoint"); engine.run(); ``` -------------------------------- ### Create a Command-Line App in Flutter Source: https://docs.flutter.dev/reference/learning-resources A command-line application sample that demonstrates parsing command-line options and fetching data from GitHub. This is useful for utility tools. ```dart import 'package:args/args.dart'; void main(List arguments) { final parser = ArgParser() ..addOption('username', abbr: 'u', defaultsTo: 'octocat'); final results = parser.parse(arguments); final username = results['username'] as String; print('Fetching data for user: $username'); // Add GitHub API fetching logic here } ``` -------------------------------- ### Set Up Universal Links for iOS Source: https://docs.flutter.dev/reference/learning-resources This recipe provides instructions on how to set up universal links for iOS applications to handle deep linking. ```swift func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool { ``` -------------------------------- ### Create a List with Headers and Items Source: https://docs.flutter.dev/reference/learning-resources This recipe explains how to create a list view that includes distinct headers followed by a series of list items. ```dart ListView.separated( itemCount: items.length, separatorBuilder: (BuildContext context, int index) => const Divider(), itemBuilder: (BuildContext context, int index) { return ItemWidget(item: items[index]); }, ) ``` -------------------------------- ### Create a List with Spaced Items Source: https://docs.flutter.dev/reference/learning-resources This recipe demonstrates how to create a list view where padding is applied between individual items. ```dart ListView.builder( padding: const EdgeInsets.all(8.0), itemCount: items.length, itemBuilder: (BuildContext context, int index) { return Container( height: 50, color: Colors.blue[100 * (index % 9)], child: Center(child: Text('Item ${index + 1}')), ); }, ) ``` -------------------------------- ### Navigation and Routing with go_router in Flutter Source: https://docs.flutter.dev/reference/learning-resources A sample demonstrating how to use the `go_router` API to handle common navigation scenarios, including deep linking and declarative routing. ```dart import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; final GoRouter router = GoRouter( routes: [ GoRoute(path: '/', builder: (context, state) => const HomePage()), GoRoute(path: '/details/:id', builder: (context, state) { final id = state.pathParameters['id']; return DetailsPage(id: id); }), ], ); class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Home Page')), body: Center( child: ElevatedButton( onPressed: () => context.go('/details/123'), child: const Text('Go to Details 123'), ), ), ); } } class DetailsPage extends StatelessWidget { final String? id; const DetailsPage({super.key, this.id}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Details Page $id')), body: Center( child: ElevatedButton( onPressed: () => context.go('/'), child: const Text('Go to Home'), ), ), ); } } // Use MaterialApp.router with this router configuration. ``` -------------------------------- ### Create and Customize Context Menus in Flutter Source: https://docs.flutter.dev/reference/learning-resources This sample demonstrates how to create and customize cross-platform context menus, such as the text selection toolbar on mobile or the right-click menu on desktop. Requires platform-specific implementations or packages. ```dart import 'package:flutter/material.dart'; // Example of showing a context menu on long press Widget buildContextMenuAwareWidget(BuildContext context) { return GestureDetector( onLongPress: () { final RenderBox overlay = Overlay.of(context)!.context.findRenderObject()! as RenderBox; final Offset tapPosition = (context.findRenderObject()! as RenderBox).localToGlobal(Offset.zero); showMenu( context: context, position: RelativeRect.fromRect সম্ভাব্য (tapPosition & const Size(40, 40), Offset.zero & overlay.size), items: >[ const PopupMenuItem(value: 'Option 1', child: Text('Option 1')), const PopupMenuItem(value: 'Option 2', child: Text('Option 2')), ], ).then((String? selectedValue) { if (selectedValue == null) return; // Handle selection print('Selected: $selectedValue'); }); }, child: Container( width: 100, height: 100, color: Colors.cyan, child: const Center(child: Text('Long Press Me')), ), ); } ``` -------------------------------- ### Persistent Storage Architecture with SQL Source: https://docs.flutter.dev/reference/learning-resources This recipe details how to save complex application data to a user's device using SQL for persistent storage. ```dart var databasePath = await getDatabasesPath(); String path = join(databasePath, 'dbs'); await deleteDatabase(path); final database = await openDatabase( path, version: 1, onCreate: (db, version) async { await db.execute( 'CREATE TABLE IF NOT EXISTS dogs (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)'); }, ); ``` -------------------------------- ### Set Up Android App Links (Deep Linking) Source: https://docs.flutter.dev/reference/learning-resources Configure deep linking on Android to allow your app to be opened directly from web links. This involves setting up intent filters in the AndroidManifest.xml. ```xml ``` -------------------------------- ### Simplify ViewModel Logic with Command Pattern Source: https://docs.flutter.dev/reference/learning-resources This recipe explains how to implement the Command pattern to simplify ViewModel logic in Flutter applications. ```dart class SaveCommand extends Command { final ViewModel viewModel; SaveCommand(this.viewModel); @override Future execute() async { await viewModel.saveData(); } } ``` -------------------------------- ### Build Transitions with Material Motion in Flutter Source: https://docs.flutter.dev/reference/learning-resources Learn to use the Material animations package to add pre-built transitions to a Material app. This codelab focuses on creating visually appealing transitions between screens. ```dart import 'package:flutter/material.dart'; // Example of using a Material transition (e.g., FadeThroughTransition) // This would typically be part of a Navigator transition setup. // Placeholder for transition usage: void navigateWithTransition(BuildContext context) { Navigator.of(context).push( PageRouteBuilder( pageBuilder: (context, animation, secondaryAnimation) => const Placeholder(), transitionsBuilder: (context, animation, secondaryAnimation, child) { return FadeTransition(opacity: animation, child: child); }, ), ); } ``` -------------------------------- ### Create and Navigate to Named Routes Source: https://docs.flutter.dev/reference/learning-resources This recipe explains the process of defining named routes and navigating to them within a Flutter application. ```dart MaterialApp( routes: { '/': (context) => const HomeScreen(), '/details': (context) => const DetailsScreen(), }, ); ``` -------------------------------- ### Work with Tabs in Material and Cupertino Source: https://docs.flutter.dev/reference/learning-resources This recipe covers common patterns for working with tabs in mobile applications, adhering to Material Design or Cupertino guidelines. ```dart DefaultTabController( length: 2, child: Scaffold( appBar: AppBar( bottom: const TabBar( tabs: [ Tab(icon: Icon(Icons.directions_car)), Tab(icon: Icon(Icons.directions_transit)), ], ), ), body: const TabBarView( children: [ Center(child: Text('Car Tab')), Center(child: Text('Transit Tab')), ], ), ), ); ``` -------------------------------- ### Add Multiplayer Support with Cloud Firestore Source: https://docs.flutter.dev/reference/learning-resources This recipe demonstrates how to implement multiplayer capabilities in a Flutter game using the cloud_firestore package. ```dart FirebaseFirestore.instance.collection('games').doc(gameId).update({'players': FieldValue.arrayUnion([playerId])}); ``` -------------------------------- ### Mock Dependencies in Tests with Mockito Source: https://docs.flutter.dev/reference/learning-resources This recipe covers the basics of mocking dependencies in Flutter tests using the Mockito package. ```dart @GenerateMocks([MyService]) class MockMyService extends Mock implements MyService {} ``` -------------------------------- ### Add a Drawer to a Screen Source: https://docs.flutter.dev/reference/learning-resources This recipe shows how to use the Drawer widget in combination with a Scaffold to create a layout featuring a Material Design drawer. ```dart Scaffold( appBar: AppBar(title: const Text('App')), drawer: Drawer( child: ListView( padding: EdgeInsets.zero, children: const [ DrawerHeader( decoration: BoxDecoration(color: Colors.blue), child: Text('Drawer Header'), ), ListTile(title: Text('Item 1')), ListTile(title: Text('Item 2')), ], ), ), body: const Center(child: Text('Content')), ); ``` -------------------------------- ### Add Achievements and Leaderboards to Game Source: https://docs.flutter.dev/reference/learning-resources This recipe explains how to integrate leaderboard functionality into a mobile game using the games_services package. ```dart GamesServices.submitScore(leaderboardID, score); ``` -------------------------------- ### Send an HTTP PUT Request Source: https://docs.flutter.dev/reference/learning-resources This recipe demonstrates how to send an HTTP PUT request to update data over the internet. ```dart final response = await http.put( Uri.parse('https://jsonplaceholder.typicode.com/posts/1'), headers: { 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode>({ 'title': 'Updated Title', 'body': 'Updated body content.', 'userId': 1, }), ); ``` -------------------------------- ### Build Animated Effects in Flutter Source: https://docs.flutter.dev/reference/learning-resources Learn to build implicit and explicit animations, and customize navigation transition animations using the animations package and predictive back on Android. Covers various animation techniques. ```dart import 'package:flutter/material.dart'; class AnimatedSquare extends StatefulWidget { const AnimatedSquare({super.key}); @override State createState() => _AnimatedSquareState(); } class _AnimatedSquareState extends State { double _size = 100; void _animate() { setState(() { _size = _size == 100 ? 200 : 100; }); } @override Widget build(BuildContext context) { return GestureDetector( onTap: _animate, child: AnimatedContainer( duration: const Duration(seconds: 1), width: _size, height: _size, color: Colors.blue, ), ); } } ``` -------------------------------- ### Write Widget Tests in Flutter Source: https://docs.flutter.dev/reference/learning-resources An introduction to writing widget tests in Flutter. Widget tests allow you to verify that your UI widgets behave as expected in isolation. ```dart import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; // Assume MyWidget is a widget you want to test void main() { testWidgets('MyWidget has a title and message', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyWidget(title: 'T', message: 'M')); // Verify that our card has the correct title and message. expect(find.text('T'), findsOneWidget); expect(find.text('M'), findsNothing); }); } class MyWidget extends StatelessWidget { final String title; final String message; const MyWidget({super.key, required this.title, required this.message}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text(title)), body: Center(child: Text(message)), ), ); } } ``` -------------------------------- ### Tap, Drag, and Enter Text in Widget Tests Source: https://docs.flutter.dev/reference/learning-resources This recipe covers interacting with widgets in Flutter widget tests, including tap gestures, drag operations, and text input. ```dart await tester.tap(find.byKey(const Key('myButton'))); await tester.drag(find.byType(Scrollable), const Offset(0, -300)); await tester.enterText(find.byType(TextField), 'Test input'); ``` -------------------------------- ### Simplistic Text Editor in Flutter Source: https://docs.flutter.dev/reference/learning-resources This sample text editor showcases the use of TextEditingDeltas and a DeltaTextInputClient to expand and contract styled ranges of text. Useful for rich text editing. ```dart import 'package:flutter/material.dart'; class SimpleTextEditor extends StatefulWidget { const SimpleTextEditor({super.key}); @override State createState() => _SimpleTextEditorState(); } class _SimpleTextEditorState extends State { final TextEditingController _controller = TextEditingController(); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return TextField( controller: _controller, decoration: const InputDecoration(hintText: 'Enter text here...'), // Add logic for TextEditingDeltas and DeltaTextInputClient if needed ); } } ``` -------------------------------- ### Animate Widget with Physics Simulation in Flutter Source: https://docs.flutter.dev/reference/learning-resources Learn how to move a widget from a dragged point back to the center using a spring simulation. This creates a natural, physics-based animation effect. ```dart import 'package:flutter/material.dart'; import 'package:flutter/physics.dart'; class PhysicsAnimationWidget extends StatefulWidget { const PhysicsAnimationWidget({super.key}); @override State createState() => _PhysicsAnimationWidgetState(); } class _PhysicsAnimationWidgetState extends State { Offset _offset = Offset.zero; final GlobalKey _widgetKey = GlobalKey(); void _animateToCenter() { final RenderBox renderBox = _widgetKey.currentContext!.findRenderObject() as RenderBox; final position = renderBox.localToGlobal(Offset.zero); final center = Offset(MediaQuery.of(context).size.width / 2, MediaQuery.of(context).size.height / 2); setState(() { _offset = Offset(center.dx - position.dx - renderBox.size.width / 2, center.dy - position.dy - renderBox.size.height / 2); }); // Simulate physics animation back to center final SpringDescription spring = SpringDescription.withDampingFromTension(tension: 100, friction: 20); final Simulation simulation = SpringSimulation(spring, _offset.dx, 0.0, 0.0); // This part requires an AnimationController or similar mechanism to actually animate the offset // For simplicity, we'll just print the intended final offset. print('Simulating animation to center. Target offset: (0, 0)'); } @override Widget build(BuildContext context) { return GestureDetector( onPanUpdate: (details) { setState(() { _offset += details.delta; }); }, onPanEnd: (details) => _animateToCenter(), child: Transform.translate( offset: _offset, child: Container( key: _widgetKey, width: 50, height: 50, color: Colors.red, ), ), ); } } ``` -------------------------------- ### Use Dart Records and Patterns in Flutter Source: https://docs.flutter.dev/reference/learning-resources Illustrates the use of Dart 3's new records and patterns features within a Flutter application for more readable and maintainable code. Requires Dart 3 or later. ```dart // Records example (String, int) record = ('Hello', 123); print(record.$1); print(record.$2); // Patterns example var data = {'name': 'Alice', 'age': 30}; if (data case {'name': String name, 'age': int age}) { print('Name: $name, Age: $age'); } ``` -------------------------------- ### Dart Extension Methods Syntax Source: https://docs.flutter.dev/reference/learning-resources Demonstrates Dart's extension method syntax. Extensions allow you to add new functionality to existing classes without modifying their source code. ```dart extension StringExtensions on String { bool get isNullOrEmpty => this.isEmpty; String capitalize() { if (isEmpty) return this; return '${this[0].toUpperCase()}${substring(1)}'; } } void main() { String message = 'hello'; print(message.capitalize()); // Output: Hello print(''.isNullOrEmpty); // Output: true } ``` -------------------------------- ### Create and Style a Text Field Source: https://docs.flutter.dev/reference/learning-resources This recipe explores the creation and styling of text fields in Flutter, covering various customization options. ```dart TextField( decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Enter text', ), ); ``` -------------------------------- ### Fetch Data from the Internet in Flutter Source: https://docs.flutter.dev/reference/learning-resources Learn to use the http package to fetch data from the internet in your Flutter application. This is a fundamental task for most dynamic apps. ```dart import 'package:http/http.dart' as http; Future fetchData() async { final url = Uri.parse('https://jsonplaceholder.typicode.com/posts'); try { final response = await http.get(url); if (response.statusCode == 200) { print('Data fetched successfully: ${response.body}'); } else { print('Failed to fetch data. Status code: ${response.statusCode}'); } } catch (e) { print('Error fetching data: $e'); } } ``` -------------------------------- ### Material Structure and Layout (MDC-102) Source: https://docs.flutter.dev/reference/learning-resources This codelab focuses on using Material Design for structure and layout in Flutter, continuing the e-commerce app from MDC-101. ```dart Scaffold( appBar: AppBar( title: const Text('E-commerce App'), ), body: Center( child: Text('Welcome!'), ), ); ``` -------------------------------- ### Make Authenticated HTTP Requests in Flutter Source: https://docs.flutter.dev/reference/learning-resources Learn how to include authorization headers in HTTP requests for authentication. This is essential for accessing protected API resources. ```dart import 'package:http/http.dart' as http; Future makeAuthenticatedRequest() async { final url = Uri.parse('https://api.example.com/data'); final token = 'YOUR_AUTH_TOKEN'; // Replace with your actual token final response = await http.get(url, headers: { 'Authorization': 'Bearer $token', 'Content-Type': 'application/json; charset=UTF-8', }); if (response.statusCode == 200) { print('Data received: ${response.body}'); } else { print('Request failed. Status code: ${response.statusCode}'); } } ``` -------------------------------- ### Pass Arguments to a Named Route Source: https://docs.flutter.dev/reference/learning-resources This recipe explains how to pass arguments to a named route and retrieve those arguments on the destination route. ```dart Navigator.pushNamed(context, '/details', arguments: {'id': itemId}); ``` -------------------------------- ### Transform Image Color Scales and Formats in Flutter Source: https://docs.flutter.dev/reference/learning-resources Demonstrates how to transform image color scales and formats. This is useful for image manipulation within a Flutter application. ```dart import 'package:flutter/material.dart'; class AssetTransformations extends StatelessWidget { const AssetTransformations({super.key}); @override Widget build(BuildContext context) { return Image.network( 'https://docs.flutter.dev/assets/images/dash/dash-fever.png', color: Colors.blueGrey, colorBlendMode: BlendMode.multiply, ); } } ``` -------------------------------- ### Grid Lists with GridView Widget Source: https://docs.flutter.dev/reference/learning-resources This recipe explains how to create and use grid layouts in Flutter applications with the GridView widget. ```dart GridView.count( crossAxisCount: 2, children: List.generate(10, (index) { return Center( child: Text( 'Item $index', style: Theme.of(context).textTheme.headlineMedium, ), ); }), ) ``` -------------------------------- ### Material Theming with Color, Shape, Elevation, and Type in Flutter Source: https://docs.flutter.dev/reference/learning-resources Discover how Material Components for Flutter simplify product differentiation and brand expression through design. This codelab focuses on applying Material Theming principles. ```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 MaterialApp( title: 'Material Theming Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, // Define other theme properties like typography, shape, elevation ), home: const MyHomePage(), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Material Theming'), ), body: const Center( child: Text('Hello World!'), ), ); } } ``` -------------------------------- ### Export Fonts from a Package Source: https://docs.flutter.dev/reference/learning-resources This recipe explains how to export and use custom fonts across multiple applications from a shared package. ```dart flutter: fonts: - family: MyCustomFont fonts: - asset: fonts/MyCustomFont.ttf ``` -------------------------------- ### Implement Offline-First Support in Flutter Source: https://docs.flutter.dev/reference/learning-resources Implement offline-first support for a feature in an application. This involves strategies for handling data when the device is offline and synchronizing when online. ```dart import 'package:flutter/material.dart'; // Placeholder for offline-first implementation class OfflineFirstFeature extends StatefulWidget { const OfflineFirstFeature({super.key}); @override State createState() => _OfflineFirstFeatureState(); } class _OfflineFirstFeatureState extends State { // State variables for offline/online status and data @override Widget build(BuildContext context) { return const Center(child: Text('Offline-First Feature Placeholder')); } } ``` -------------------------------- ### Fade In Images with Placeholder using FadeInImage Source: https://docs.flutter.dev/reference/learning-resources This recipe utilizes the FadeInImage widget to display a visual placeholder while an image is loading. ```dart FadeInImage.memoryNetwork( placeholder: kTransparentImage, image: 'https://example.com/image.jpg', ); ``` -------------------------------- ### Handle Scrolling in Flutter Widget Tests Source: https://docs.flutter.dev/reference/learning-resources Learn how to simulate and handle scrolling behavior within Flutter widget tests. This is crucial for testing scrollable widgets like ListViews. ```dart import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; // Assume a widget with a Scrollable is present // Example test snippet: // testWidgets('Scrollable widget test', (WidgetTester tester) async { // await tester.pumpWidget(MyScrollableWidget()); // await tester.scrollUntilVisible( // find.text('Target Item'), // 50.0, // scroll offset // scrollable: find.byType(Scrollable), // ); // expect(find.text('Target Item'), findsOneWidget); // }); ``` -------------------------------- ### Create an Expandable FAB in Flutter Source: https://docs.flutter.dev/reference/learning-resources Create a floating action button (FAB) that expands to reveal other action buttons. This pattern is useful for providing quick access to related actions. ```dart import 'package:flutter/material.dart'; class ExpandableFAB extends StatefulWidget { const ExpandableFAB({super.key}); @override State createState() => _ExpandableFABState(); } class _ExpandableFABState extends State { bool _isOpen = false; void _toggleMenu() { setState(() { _isOpen = !_isOpen; }); } @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.end, children: [ if (_isOpen) ...[ FloatingActionButton(onPressed: () {}, child: const Icon(Icons.star)), const SizedBox(height: 8), FloatingActionButton(onPressed: () {}, child: const Icon(Icons.favorite)), const SizedBox(height: 8), ], FloatingActionButton( onPressed: _toggleMenu, child: Icon(_isOpen ? Icons.close : Icons.add), ), ], ); } } ``` -------------------------------- ### Save Key-Value Data in Flutter Source: https://docs.flutter.dev/reference/learning-resources Demonstrates how to save application data to a user's on-device key-value store using the shared_preferences package. This is suitable for small amounts of data. ```dart import 'package:shared_preferences/shared_preferences.dart'; Future saveData() async { final prefs = await SharedPreferences.getInstance(); await prefs.setString('username', 'JohnDoe'); print('Data saved'); } Future loadData() async { final prefs = await SharedPreferences.getInstance(); final username = prefs.getString('username'); print('Loaded username: $username'); } ``` -------------------------------- ### Navigate to a New Screen and Back with Navigator Source: https://docs.flutter.dev/reference/learning-resources This recipe utilizes the Navigator widget to manage navigation between different screens or routes in a Flutter application. ```dart Navigator.push( context, MaterialPageRoute(builder: (context) => const SecondScreen()), ); ``` -------------------------------- ### Display Images from the Internet in Flutter Source: https://docs.flutter.dev/reference/learning-resources To display images from a URL, use the Image.network() constructor. Ensure the image URL is valid and accessible. ```dart Image.network('https://example.com/image.jpg') ``` -------------------------------- ### Add AdMob Banner and Native Ads in Flutter Source: https://docs.flutter.dev/reference/learning-resources Learn to implement inline banner and native ads within a travel booking app using AdMob. This codelab focuses on integrating ads into existing app structures. ```dart import 'package:flutter/material.dart'; // Assume AdMob related imports and setup are done elsewhere class AdMobBannerWidget extends StatelessWidget { const AdMobBannerWidget({super.key}); @override Widget build(BuildContext context) { // Placeholder for AdMob banner widget return Container( height: 50, color: Colors.grey, child: const Center(child: Text('AdMob Banner')), ); } } ``` -------------------------------- ### Return Data from a Screen in Flutter Source: https://docs.flutter.dev/reference/learning-resources Return data from one screen to another using the Navigator.pop method. This is commonly used after a user completes an action on a secondary screen. ```dart Navigator.pop(context, 'Data to return'); ``` -------------------------------- ### Check App Orientation in Widget Tests Source: https://docs.flutter.dev/reference/learning-resources This recipe shows how to check the current orientation of the application within widget tests. ```dart final orientation = widget.orientation; expect(orientation, Orientation.portrait); ``` -------------------------------- ### Find Widgets in Tests with flutter_test Source: https://docs.flutter.dev/reference/learning-resources This recipe examines the 'find' constant provided by the flutter_test package for locating widgets during testing. ```dart final textFinder = find.text('Hello World'); expect(textFinder, findsOneWidget); ``` -------------------------------- ### Implement Swipe to Dismiss with Dismissible Widget Source: https://docs.flutter.dev/reference/learning-resources This recipe teaches how to implement the swipe-to-dismiss functionality using the Dismissible widget in Flutter. ```dart Dismissible( key: Key(item.id.toString()), onDismissed: (direction) { // Remove the item from data source }, child: ListTile(title: Text(item.name)), ) ``` -------------------------------- ### Report Errors to Sentry Crash Reporting Source: https://docs.flutter.dev/reference/learning-resources This recipe demonstrates how to integrate Sentry for reporting errors in your Flutter application. ```dart SentryFlutter.init( (options) { options.dsn = 'YOUR_SENTRY_DSN'; }, appRunner: () => runApp(const MyApp()), ); ``` -------------------------------- ### Lists and Floating App Bars in Flutter Source: https://docs.flutter.dev/reference/learning-resources Arrange a floating app bar or navigation bar above a list. This layout pattern is common for apps with scrollable content and persistent headers. ```dart import 'package:flutter/material.dart'; Scaffold( body: CustomScrollView( slivers: [ const SliverAppBar( title: Text('Floating App Bar'), floating: true, ), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return ListTile(title: Text('Item $index')); }, childCount: 50, ), ), ], ), ) ``` -------------------------------- ### Create Nested Navigation Flows in Flutter Source: https://docs.flutter.dev/reference/learning-resources Define top-level routes and routes nested below specific widgets to create complex navigation structures. This is often managed using packages like go_router. ```dart import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; // Define top-level routes final GoRouter _router = GoRouter( routes: [ GoRoute( path: '/', builder: (context, state) => const HomeScreen(), routes: [ // Nested routes GoRoute( path: 'details', builder: (context, state) => const DetailsScreen(), ), ], ), ], ); class HomeScreen extends StatelessWidget { const HomeScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Home')), body: Center( child: ElevatedButton( onPressed: () => context.go('/details'), child: const Text('Go to Details'), ), ), ); } } class DetailsScreen extends StatelessWidget { const DetailsScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Details')), body: Center( child: ElevatedButton( onPressed: () => context.go('/'), child: const Text('Go to Home'), ), ), ); } } // In your MaterialApp.router: // router: _router ``` -------------------------------- ### Implement Drag-and-Drop in Flutter Source: https://docs.flutter.dev/reference/learning-resources Builds a drag-and-drop interaction where a UI element can be moved by the user after a long press. This utilizes GestureDetector for input handling. ```dart import 'package:flutter/material.dart'; class DraggableWidget extends StatefulWidget { const DraggableWidget({super.key}); @override State createState() => _DraggableWidgetState(); } class _DraggableWidgetState extends State { Offset _offset = Offset(0, 0); @override Widget build(BuildContext context) { return Positioned( left: _offset.dx, top: _offset.dy, child: GestureDetector( onLongPressMoveUpdate: (details) { setState(() { _offset += details.delta; }); }, child: Container( width: 100, height: 100, color: Colors.blue, ), ), ); } } ``` -------------------------------- ### Scrolling Parallax Effect with Cards and Images Source: https://docs.flutter.dev/reference/learning-resources This recipe shows how to create a parallax scrolling effect by building a list of cards with images that move at different speeds. ```dart ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return ParallaxWidget(item: items[index]); }, ) ``` -------------------------------- ### Animate a Widget Across Screens in Flutter Source: https://docs.flutter.dev/reference/learning-resources Use the Hero widget to create a smooth, animated transition for a widget as it moves from one screen to another. This enhances the user experience by visually linking related elements. ```dart import 'package:flutter/material.dart'; // On the source screen: // Hero( // tag: 'hero-tag', // child: Image.network('your_image_url'), // ) // On the destination screen: // Hero( // tag: 'hero-tag', // child: Image.network('your_image_url'), // ) ``` -------------------------------- ### Display a Snackbar in Flutter Source: https://docs.flutter.dev/reference/learning-resources Use the ScaffoldMessenger to display a Snackbar widget, providing user feedback for actions. This is commonly used for confirmations or brief messages. ```dart ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Message displayed'))); ``` -------------------------------- ### Add Google Maps to Flutter App Source: https://docs.flutter.dev/reference/learning-resources This codelab covers displaying a Google Map, retrieving data from a web service, and showing that data as markers on the map. ```dart GoogleMap(initialCameraPosition: _kGooglePlex) ``` -------------------------------- ### Add User Authentication with FirebaseUI Source: https://docs.flutter.dev/reference/learning-resources This codelab shows how to quickly add Firebase authentication to a Flutter app using FirebaseUI, requiring minimal code. ```dart FirebaseUI.configure( emailVisible: true, passwordVisible: true, // ... other configurations ); ``` -------------------------------- ### Add In-App Purchases to Flutter App Source: https://docs.flutter.dev/reference/learning-resources Extend a simple gaming app to offer three types of in-app purchases: consumable, non-consumable, and subscription. Requires integration with store APIs (e.g., RevenueCat or store_redirect). ```dart import 'package:flutter/material.dart'; // Placeholder for in-app purchase logic Future purchaseConsumable() async { print('Attempting to purchase consumable...'); // Add purchase logic using a plugin like revenue_cat or store_redirect } Future purchaseNonConsumable() async { print('Attempting to purchase non-consumable...'); // Add purchase logic } Future purchaseSubscription() async { print('Attempting to purchase subscription...'); // Add purchase logic } ``` -------------------------------- ### Handle Taps in Flutter Source: https://docs.flutter.dev/reference/learning-resources Use the GestureDetector widget to respond to fundamental user actions, such as tapping and dragging. It provides callbacks for various gestures. ```dart import 'package:flutter/material.dart'; GestureDetector( onTap: () { print('Widget tapped!'); }, onLongPress: () { print('Widget long pressed!'); }, child: Container( width: 100, height: 100, color: Colors.green, ), ) ``` -------------------------------- ### Send HTTP POST Request in Flutter Source: https://docs.flutter.dev/reference/learning-resources Send HTTP POST requests in your Flutter app using the http package. This is commonly used for submitting data to a server. ```dart import 'package:http/http.dart' as http; import 'dart:convert'; Future postData() async { final url = Uri.parse('https://jsonplaceholder.typicode.com/posts'); final response = await http.post( url, headers: { 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode({ 'title': 'foo', 'body': 'bar', 'userId': '1', }), ); if (response.statusCode == 201) { print('Data posted successfully: ${response.body}'); } else { print('Failed to post data. Status code: ${response.statusCode}'); } } ``` -------------------------------- ### Shift Focus to a Text Field Programmatically Source: https://docs.flutter.dev/reference/learning-resources This recipe demonstrates how to programmatically shift the focus to a specific text field within your Flutter application. ```dart FocusScope.of(context).requestFocus(_focusNode); ``` -------------------------------- ### Work with Long Lists in Flutter Source: https://docs.flutter.dev/reference/learning-resources Efficiently work with long lists of data using the ListView.builder constructor. This widget builds items lazily as they are needed, improving performance. ```dart import 'package:flutter/material.dart'; ListView.builder( itemCount: 1000, // Example item count itemBuilder: (BuildContext context, int index) { return ListTile( title: Text('Item $index'), ); }, ) ``` -------------------------------- ### Send HTTP DELETE Request in Flutter Source: https://docs.flutter.dev/reference/learning-resources Use the http package to send an HTTP DELETE request to a specified URL. Ensure the http package is added to your pubspec.yaml. ```dart import 'package:http/http.dart' as http; Future deleteData() async { final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1'); final response = await http.delete(url); if (response.statusCode == 200) { print('Data deleted successfully'); } else { print('Failed to delete data. Status code: ${response.statusCode}'); } } ``` -------------------------------- ### Error Handling with Result Objects in Flutter Source: https://docs.flutter.dev/reference/learning-resources Improve error handling across classes with Result objects. This pattern provides a structured way to represent success or failure outcomes of operations. ```dart sealed class Result { const Result(); factory Result.success(T value) = Success; factory Result.failure(E error) = Failure; } class Success extends Result { final T value; const Success(this.value); } class Failure extends Result { final E error; const Failure(this.error); } // Example usage: Result mightFail() { try { // Some operation that might fail return const Result.success('Operation successful!'); } catch (e) { return Result.failure('Operation failed: $e'); } } void main() { final result = mightFail(); switch (result) { case Success(value: final String message): print('Success: $message'); case Failure(error: final String errorMessage): print('Failure: $errorMessage'); } } ``` -------------------------------- ### Add WebView to Flutter App Source: https://docs.flutter.dev/reference/learning-resources Integrate a WebView widget into your Android or iOS Flutter app using the webview_flutter plugin. This allows displaying web content within your application. ```dart import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; // Ensure you have added the webview_flutter dependency class WebViewScreen extends StatefulWidget { const WebViewScreen({super.key}); @override State createState() => _WebViewScreenState(); } class _WebViewScreenState extends State { late final WebViewController controller; @override void initState() { super.initState(); controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setBackgroundColor(const Color(0x00000000)) ..setNavigationDelegate( NavigationDelegate( onPageStarted: (String url) {}, onPageFinished: (String url) {}, onWebResourceError: (WebResourceError error) {}, ), ) ..loadRequest(Uri.parse('https://flutter.dev')); } @override Widget build(BuildContext context) { return WebViewWidget(controller: controller); } } ``` -------------------------------- ### Add Material Touch Ripples in Flutter Source: https://docs.flutter.dev/reference/learning-resources Use the InkWell widget to display a ripple animation effect when the user interacts with a UI element, such as tapping. This provides visual feedback for touch events. ```dart import 'package:flutter/material.dart'; InkWell( onTap: () { print('Tapped!'); }, child: Container( padding: const EdgeInsets.all(16.0), color: Colors.blue, child: const Text('Tap Me'), ), ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.