| AnimationController() | Tween() |
|---|---|
| An AnimationController is responsible for controlling the animation's behavior. It lets you define the duration, start, stop, reverse, and repeat the animation. | A Tween defines the range of values that an animation should interpolate between. It doesn't perform animation itself but specifies the start ( begin ) and end ( end ) values for the controller to animate. |
| Key Properties | Key Properties |
| duration: Specifies how long the animation should last. | begin: The starting value of the animation. |
vsync : Reduces unnecessary CPU/GPU work by syncing animation with the screen's refresh rate. It's mandatory and typically provided by using SingleTickerProviderStateMixin . | end: The final value after the animation completes. |
How to use AnimationController()?- Create an AnimationController in the initState() method.- Control the animation with methods like forward() , reverse() , or repeat() . | How to use Tween()?- Pair a Tween with an AnimationController .- Use .animate() to bind the Tween to the controller. |
import 'package:flutter/material.dart';
class ImplicitAnimationExample extends StatefulWidget {
@override
_ImplicitAnimationExampleState createState() => _ImplicitAnimationExampleState();
}
class _ImplicitAnimationExampleState extends State<ImplicitAnimationExample> {
double _size = 100;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GestureDetector(
onTap: () {
setState(() {
_size = _size == 100 ? 200 : 100; // Change size on tap
});
},
child: AnimatedContainer(
width: _size,
height: _size,
color: Colors.blue,
duration: Duration(seconds: 1), // Animation duration
),
),
),
);
}
}import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Explicit Animation Example',
home: AnimationExample(),
);
}
}
class AnimationExample extends StatefulWidget {
@override
_AnimationExampleState createState() => _AnimationExampleState();
}
class _AnimationExampleState extends State<AnimationExample> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
bool _isAnimating = false;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
_animation = Tween<double>(begin: 0, end: 300).animate(_controller)
..addListener(() {
setState(() {});
});
}
void _startAnimation() {
if (!_isAnimating) {
_isAnimating = true;
_controller.forward(from: 0).then((_) {
_isAnimating = false; // Resetting the flag after animation completes
});
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Explicit Animation'),
),
body: GestureDetector(
onTap: _startAnimation,
child: Center(
child: Container(
margin: EdgeInsets.only(left: _animation.value),
width: 100,
height: 100,
color: Colors.blue,
),
),
),
);
}
}AnimationController manages the timing of the animation (when it starts, how long it lasts, and its progress).duration and vsync to sync with the screen's refresh rate._controller = AnimationController(
duration: Duration(seconds: 2),
vsync: this,
);Tween defines the range of values to interpolate between, such as size, color, or opacity. It doesn't animate itself but works with the AnimationController ._animation = Tween<double>(begin: 100, end: 300).animate(_controller);AnimatedBuilder or similar widgets to rebuild the UI based on the current value of the animation. The widget changes dynamically as the animation progresses.AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Container(
width: _animation.value, // Animation value updates over time
height: _animation.value,
color: Colors.blue,
);
},
);forward() , reverse() , or repeat() ._controller.forward(); // Starts the animationAnimationController when it's no longer needed to free up resources@override
void dispose() {
_controller.dispose();
super.dispose();
}import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Spring Animation Example',
home: AnimationExample(),
);
}
}
class AnimationExample extends StatefulWidget {
@override
_AnimationExampleState createState() => _AnimationExampleState();
}
class _AnimationExampleState extends State<AnimationExample> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 2000),
vsync: this,
)..addListener(() {
setState(() {});
});
_animation = Tween<double>(begin: 0, end: 300).animate(
CurvedAnimation(
parent: _controller,
curve: Curves.elasticOut,
),
);
}
void _startAnimation() {
_controller.forward(from: 0).then((_) {
// Animation completed
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Spring Animation'),
),
body: GestureDetector(
onTap: _startAnimation,
child: Center(
child: Container(
margin: EdgeInsets.only(left: _animation.value),
width: 100,
height: 100,
color: Colors.blue,
),
),
),
);
}
}pubspec.yaml filedependencies:
http: ^0.13.3 # Example of the HTTP package for network
requestsimport 'package:http/http.dart' as http;
var response = await http.get(Uri.parse('https://packagelin
k.com'));Pub.dev website: which is the official package repository for Dart and Flutter.pubspec.yaml : This file is located in the root directory of your Flutter project.dependencies section, add the package name and version. You can specify a version or use a caret (^) to allow updates.dependencies:
flutter:
sdk: flutter
http: ^0.13.3 # Example: Adding the HTTP packageSave the File: After adding the package, save the pubspec.yaml file. This action will trigger Flutter to download the package.
Import the Package:
import statement.import 'package:http/http.dart' as http; // Importing the HTTP packageimport 'package:flutter/material.dart';
import 'package:http/http.dart' as http; // Importing the HTTP package
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'HTTP Package Example',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _data = "Press the button to fetch quote";
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://dummyjson.com/quotes/random'));
if (response.statusCode == 200) {
final Map<String, dynamic> data = json.decode(response.body);
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Quote'),
content: Text("${data['quote']} \n\n-${data['author']}"),
actions: [
TextButton(
child: Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
} else {
throw Exception('Failed to load data');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('HTTP Package Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_data),
SizedBox(height: 20),
ElevatedButton(
onPressed: fetchData,
child: Text('Fetch Quote'),
),
],
),
),
);
}
}flutter create --template=plugin my_flutter_plugin to scaffold a new plugin projectlib/my_flutter_plugin.dart : The main Dart file for the plugin API.android/src/main/kotlin/... : Android-specific implementation.ios/Classes/MyFlutterPlugin.swift : iOS-specific implementation.lib/my_flutter_plugin.dart , specifying methods that will be callable from Flutter.pubspec.yaml .Accessing a REST API in Flutter involves sending HTTP requests to a server and handling the responses. Here's a step-by-step guide on how to do it, along with explanations of each part.
http package to your project. This package simplifies making HTTP requests.pubspec.yaml file.dependencies :dependencies:
flutter:
sdk: flutter
http: ^0.13.3 # Check for the latest version on pub.devSave the file and run flutter pub get to install the package.
Step-02: Import the Package:
import 'package:http/http.dart' as http;Future<void> fetchData() async {
final response = await http.get(Uri.parse('<https://jsonplaceholder.typicode.com/posts>'));
if (response.statusCode == 200) {
// If the server returns a 200 OK response, parse the data
print(response.body); // Handle the response data
} else {
// If the server does not return a 200 OK response, throw an error
throw Exception('Failed to load data');
}
}fetchData function within your Flutter app, for example, in the initState method of a stateful widget.@override
void initState() {
super.initState();
fetchData(); // Call the fetch function when the widget
initializes
}dart:convert package to decode it.import 'dart:convert'; // Import for JSON parsing
import 'package:http/http.dart' as http; // Import for HTTP requests
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
// Decode the JSON response
List<dynamic> data = json.decode(response.body);
print(data); // Do something with the data
} else {
throw Exception('Failed to load data');
}
}dart:convert to parse the JSON response into Dart objects. You can map the JSON data to a Dart model class for easier accesssqflite package provides a way to interact with SQLite databases. It allows you to perform operations like creating tables, inserting, updating, querying, and deleting data in a local database stored on the device.sqflite and path Packages:
dependencies:
sqflite: ^2.0.0+4 # Ensure you're using the latest version
path: ^1.8.0 # Required to define database pathImport the Required Packages:
sqflite to interact with the database and path to help find the correct location for storing the database.Create a Database:
openDatabase() function to open or create a database. You define the database schema by creating tables using SQL.Perform CRUD Operations:
Close the Database:
close() function.pubspec.yamlmain() function.flutter_localizations and intl in your pubspec.yamlMaterialApp widget..arb (Application Resource Bundle) files (JSON-like) for each language with key-value pairs for translations.LocalizationDelegates: Set up delegates to load the appropriate localized resources.flutter_test package, allowing you to build a widget in a test environment and interact with it.integration_test package, which runs tests on a real device or emulator.WidgetTester to interact with widgets in a test environment.pubspec.yaml : Ensure all dependencies are up to date and set your app version and build number.build/app/outputs/apk/release/ directory.flutter build apk --releasekeytool -genkey -v -keystore your_keystore_name.jks - keyalg RSA -keysize 2048 -validity 10000 -alias your_ alias_nameandroid/app/build.gradle file with the signing configuration:android {
...
signingConfigs {
release {
keyAlias 'your_alias_name'
keyPassword 'your_key_password'
storeFile file('path_to_your_keystore.jks')
storePassword 'your_store_password'
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}flutter build apk --releaseadb install build/app/outputs/apk/release/app-release.ap kMade By SOU Student for SOU Students