Flutter - Relative Position Animations - animation

Oops guys, how are you?
I am making an app using flutter and came across an issue related to animations.
Based on my study I wanted to make an animation where a center image on the screen after the animation is on top (topcenter).
But I didn't find a way to animate using relative values (for example the actual screen height value) only with values that I would describe (which causes problems on screens with different sizes).
Does anyone have any solutions?
AnimatedLogo({this.controller}) :
imagePosition = Tween(
begin: (Use screen size here without context),
end: (0 to topcenter)
).animate(
CurvedAnimation(
parent: controller,
curve: Interval(0.0, 0.150),
)
);

You have some options, you can use AnimatedContainer or AnimatedPositioned
All these options can use AlignmentDirectional.bottomCenter , topCenter
For other options, you can reference this https://medium.com/aubergine-solutions/options-to-animate-in-flutter-2cec6612c207
full code with AnimatedContainer
import 'package:flutter/material.dart';
import 'dart:ui';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: Option5()
);
}
}
class Option5 extends StatefulWidget {
#override
_Option5State createState() => _Option5State();
}
class _Option5State extends State<Option5> with TickerProviderStateMixin {
AlignmentDirectional _ironManAlignment = AlignmentDirectional.bottomCenter; //AlignmentDirectional(0.0, 0.7);
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/person-96.png'),
fit: BoxFit.cover)),
),
AnimatedContainer(
duration: Duration(seconds: 3),
alignment: _ironManAlignment,
child: Container(
height: 250,
width: 150,
child: Image.asset('assets/images/alarm-80.png'),
),
),
Align(
alignment: AlignmentDirectional.bottomCenter,
child: RaisedButton(
onPressed: () {
_flyIronMan();
},
child: Text('Go'),
color: Colors.red,
textColor: Colors.yellowAccent,
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20))),
),
)
],
);
}
void _flyIronMan() {
setState(() {
_ironManAlignment = AlignmentDirectional.topCenter; //AlignmentDirectional(0.0,-0.7);
});
}
}

Related

How to remove these lines between Row children

I'm new to flutter, and I'm trying to divide the screen into three parts, here's my attempt:
class Homepage extends Statelesswidget {
const HomePage({Key? key}): super (key: key);
#override
Widget build(BuildContext context) {
return Row(children: [
const Expanded(
flex: 1,
child: Scaffold(
body: Center(child: Text("Left")),
), // Scaffold
), // Expanded
Expanded(
flex: 2,
child: Scaffold(
appBar: AppBar(),
body: const Center(child: Text("Middle")),
), // Scaffold
), // Expanded
const Expanded(
flex: 1,
child: Scaffold(
body: Center(child: Text("Right")),
), // Scaffold
) // Expanded
]);
}
}
and main.dart looks like:
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
);
}
}
Here's the result:
I got these vertical lines out of nowhere, how can I get rid of them?
Welcome to Flutter 💙
These lines are the boarders of the Scaffold widget which you are using inside each Expanded widget in the row.
Now intead of looking for a way to remove these border lines, I suggest you to learn more about the Scaffold widget in Flutter
Since you are new to Flutter, you have to be aware with the goal of using Scaffold widget, which is stated in the official docs as the following:
Implements the basic material design visual layout structure.
This class provides APIs for showing drawers and bottom sheets.
So in other words, we use the Scaffold Widget as a basic canvas for the screen with some properties to implement popular layout designs, such as AppBar, BottomNavigationBar, FloatingActionButton, etc...
Then, we use it once in the screen to set the basic layout, and does not required to be used multiple times for each sub part of the screen
Then your HomePage code should be something like:
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Row(children: [
const Expanded(
flex: 1,
child: Center(child: Text("Left")),
), // Expanded
Expanded(
flex: 2,
child: Column(
children: [
AppBar(),
const Expanded(
child: Center(child: Text("Middle")),
),
],
),
),
const Expanded(
flex: 1,
child: Center(child: Text("Right")),
)
]),
);
}
}

flutter - bad perf- advice

I'm developing my first app with flutter. At some point I was wondering :Am I developping the UX part correctly ? Meaning am I using the proper widget, is there any better way to do that etc.. I find out about Flutter Performance on Intellj Idea and I saw that most of the pages I developed are red...
FYI : The code I created for a simple page
Flutter inspector result => radio-btn-aligned
import 'package:flutter/material.dart';
import 'package:testapp/my_theme.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: MyAppTheme(ctx: context).defaultTheme,
home: new Scaffold(
appBar: new AppBar(
title: new Text("Title"),
),
body: AddDailyTaskPage()),
);
}
}
enum Options { goal, category }
class AddDailyTaskPage extends StatefulWidget {
#override
_AddDailyTaskPageState createState() => new _AddDailyTaskPageState();
}
class _AddDailyTaskPageState extends State<AddDailyTaskPage> {
Options _options = Options.goal;
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Container(
child: Text("Task Description"),
),
Container(child: Row(
children: [
Expanded(
child: Row(
children: [
Radio<Options>(
value: Options.goal,
groupValue: _options,
onChanged: (Options value) {
setState(() {
_options = value;
});
},
),
Text(
'Goal',
style: new TextStyle(fontSize: 16.0),
)
]
)
),
Expanded(
child: Row(
children: [
Container(
child: Radio(
value: Options.category,
groupValue: _options,
onChanged: (Options value) {
setState(() {
_options = value;
});
},
),
),
Container(
child: Text(
'Category',
style: new TextStyle(
fontSize: 16.0,
),
),
)
],
)
)
],
),)
// Container(
// child: TextField(
// maxLines: 10,
// decoration: InputDecoration(
// // suffixIcon:
// focusedBorder: OutlineInputBorder(
// borderSide: BorderSide(color: Colors.grey, width: 5.0),
// ),
// enabledBorder: OutlineInputBorder(
// borderSide: BorderSide(color: Colors.black, width: 5.0),
// ),
// hintText: 'Description task',
// ),
// ),
// )
],
),
);
}
}
To see the difference, I checked the sample code provided while creating a flutter Project
FYI :
flutter performance result : auto-increment
As we can see on the previous pic, it doesn't seems optimised.. :/
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Few questions :
1/ Does anyone has / knows a good flutter repo with ton of examples based on performance ?
2/ What is your standard in term of perf ? I mean on my virtual device, the UX seems fluid but if the Flutter Perf is "red", then I'm guessing I'm doing something wrong and there is a better way to do ?
3/ Do you guys knows a website / forum / someone who's willing to do a core review once a week to help me implementing good pattern in my flutter application ?
4/ What is wrong with my current design ? What is wrong with the default design ? Why the performance are doesn't seems good ? I started to read the official documentation for the perf, but how could I know if the UX itself have good perf or not ? Actually by testing some stuff, I find out that putting everything in Container / Row or Column widget, improved a lot the performance but even with this widgets, it's not enough :/
Any advice ?
Thanks for your help
You use a StatefulWidget for the whole page. That means that when you call setState() the whole page gets rebuild.
One example is:
Radio<Options>(
value: Options.goal,
groupValue: _options,
onChanged: (Options value) {
setState(() {
_options = value;
});
},
),
There's no need to rebuild your whole page when you set an option. If you extract that code out into it's own StatefulWidget, only this portion gets rebuild.
You can click on "Track Widget rebuilds" to see what Widgets do rebuild in your app and then think about whether those Widget actually should rebuild.
Once you do smaller Widgets you get the problem that events in one Widget are supposed to influence other Widgets. That's when state management solutions come into play. The weather example of the Bloc package shows a good structure of an app that you can copy.

How to add a text to an image in flutter

How to add a text to an image in flutter web
How do I add text on the go to an image on flutter web? Is there widget for image editing. How can we achieve this?
You can use either custom painting (other answer found by #F-1) or stack other widget on top of your image (here is excellent example, with text on top of images as you might want.
import 'package:flutter/material.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Add Text to an Image"),
),
body:Container(
margin: EdgeInsets.only(top: 50.0),
child: Stack(
children: <Widget>[
Image.network("http://www.panama-offshore-services.com/wp-
content/uploads/2014/08/Tech-business-panama.jpg"),
Container(
margin: EdgeInsets.only(top:20.0),
),
Text("This is text",
style: TextStyle(
color: Colors.red,
fontSize: 18.0
),)
],
),
)
),
);
}
}
// use stack to add text on image

How to animate widget after the app is launched

I want to animate my container height after launching the application (after the widget tree is rendered and shown on screen). For example, animate height from 86 to 210.
What I have tried:
class MyAppState extends State<HomePage> with TickerProviderStateMixin {
double appBarHeight = 86.0;
#override
void initState() {
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => animate());
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
AnimatedContainer(
curve: Curves.fastOutSlowIn,
child: Container(
color: Colors.red,
),
height: appBarHeight,
duration: Duration(milliseconds: 400),
),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: EdgeInsets.only(right: 16.0, bottom: 16.0),
child: FloatingActionButton(
child: Icon(Icons.brush),
onPressed: () {
animate();
},
),
))
],
),
);
}
void animate(){
setState(() {
if (appBarHeight == 210.0) appBarHeight = 86.0;
else appBarHeight = 210.0;
});
}
}
But it does not work, because widget is animated before appearing on screen. I see white screen while app is launching and then my widget appears on screen with a final height.
In Android for this purpose we can use addOnLayoutChangeListener().
Is there an analogue of addOnLayoutChangeListener() in Flatter?
As you mentioned, looks like it's an issue on Android, I tested on iOS and the animation runs at the beginning.
You can try this workaround :
_startAnimation(_) async {
await Future.delayed(Duration(milliseconds: 200));
animate();
}
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback(_startAnimation);
}

Animate ListView item to full screen in Flutter

I would like to have my list items perform this animation (mp4) when tapped. I tried using AnimatedCrossFade but it requires its two children to be at the same level, e.g. the detail view cross-fades with the ListView not the tapped item. In fact it seems a Hero animation is the only one that can animate across widgets.
I'm having trouble using Hero. Should it wrap the list item? Does it matter if the Widget subtree is significantly different in the Hero source/destination? Also, can Hero animations be used with LocalHistoryRoutes or staggered animations?
Edit
It's now looking like what I need to do is use an Overlay, the hard part there is that I need to add the selected item to the overlay at the same position on screen where it was tapped, then the animation part would be easy. Possibly of use here is a target/follower pattern e.g. CompositedTransformTarget
You can just use Hero widget to make that kind of animation. Here's my example:
and the source code:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new FirstPage(title: 'Color Palette'),
);
}
}
class FirstPage extends StatefulWidget {
FirstPage({Key key, this.title}) : super(key: key);
final String title;
#override
_FirstPageState createState() => new _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
final palette = [
{'#E53935': 0xFFE53935},
{'#D81B60': 0xFFD81B60},
{'#8E24AA': 0xFF8E24AA},
{'#5E35B1': 0xFF5E35B1},
{'#3949AB': 0xFF3949AB},
{'#1E88E5': 0xFF1E88E5},
{'#039BE5': 0xFF039BE5},
{'#00ACC1': 0xFF00ACC1},
{'#00897B': 0xFF00897B},
{'#43A047': 0xFF43A047},
{'#7CB342': 0xFF7CB342},
{'#C0CA33': 0xFFC0CA33},
];
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Container(
child: new ListView.builder(
itemCount: palette.length,
itemBuilder: (context, index) => new Hero(
tag: palette[index].keys.first,
child: new GestureDetector(
onTap: () {
Navigator
.of(context)
.push(new ColorPageRoute(palette[index]));
},
child: new Container(
height: 64.0,
width: double.infinity,
color: new Color(palette[index].values.first),
child: new Center(
child: new Hero(
tag: 'text-${palette[index].keys.first}',
child: new Text(
palette[index].keys.first,
style: Theme.of(context).textTheme.title.copyWith(
color: Colors.white,
),
),
),
),
),
),
)),
),
);
}
}
class SecondPage extends StatelessWidget {
final Map<String, int> color;
SecondPage({this.color});
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Color'),
),
body: new Hero(
tag: color.keys.first,
child: new Container(
color: new Color(color.values.first),
child: new Center(
child: new Hero(
tag: 'text-${color.keys.first}',
child: new Text(
color.keys.first,
style:
Theme.of(context).textTheme.title.copyWith(color: Colors.white),
),
),
),
),
),
);
}
}
class ColorPageRoute extends MaterialPageRoute {
ColorPageRoute(Map<String, int> color)
: super(
builder: (context) => new SecondPage(
color: color,
));
#override
Widget buildTransitions(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation, Widget child) {
return FadeTransition(opacity: animation, child: child);
}
}
Someone wrote an amazing dart-package for just this purpose: https://pub.dev/packages/morpheus#-readme-tab-
All you then need to do is use the MorpheusPageRoute and the package handles the rest.
...
Navigator.push(
context,
MorpheusPageRoute(
builder: (context) => MyWidget(title: title),
),
);
...
I'd just cheat and wrap the whole thing in a Stack - bottom layer would be a page with the AppBar, and the top layer would be transparent until painted on.
onTap, duplicate ListTile onto the top surface, and then a Hero animation would fill the full screen. It's not very elegant, but the framework doesn't (yet) provide for covering the AppBar easily, so having a canvas ready to be painted on for other tricky animations might be resourceful.
I'm unable to comment or edit Lucas' post (new account) but you also need to provide the parentKey of the widget where the animation is to begin:
final widgetKey = GlobalKey();
...
ListTile(
key: widgetKey,
title: Text('My ListItem'),
onTap: () => Navigator.push(
context,
MorpheusPageRoute(
builder: (context) => MyNewPage(),
parentKey: widgetKey,
),
),
),
https://pub.dev/packages/morpheus

Resources