I need to get a context for my Navigator push, i have this Navigator on my function _navigate. I try something like _navigate(BuildContext context) but i got an error like "type (BuildContext) => dynamic is not a subtype of type() => void. It's the first context of Navigator.push i don't know how to get it.
import 'package:flutter/material.dart';
import 'package:pandora_etna/assistance.dart';
import 'dart:math';
import 'package:vector_math/vector_math.dart' show radians;
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Color(0xFFB3E5FC),
body: SizedBox.expand(child: RadialMenu())),
);
}
}
class RadialMenu extends StatefulWidget {
createState() => _RadialMenuState();
}
class _RadialMenuState extends State<RadialMenu>
with SingleTickerProviderStateMixin {
AnimationController controller;
void initState() {
super.initState();
controller =
AnimationController(duration: Duration(milliseconds: 900), vsync: this);
}
Widget build(BuildContext context) {
return RadialAnimation(controller: controller);
}
}
class RadialAnimation extends StatelessWidget {
RadialAnimation({Key key, this.controller})
: scale = Tween<double>(
begin: 1.5,
end: 0.0,
).animate(
CurvedAnimation(parent: controller, curve: Curves.fastOutSlowIn),
),
translation = Tween<double>(
begin: 0.0,
end: 100.0,
).animate(
CurvedAnimation(parent: controller, curve: Curves.linear),
),
rotation = Tween<double>(begin: 0.0, end: 360.0).animate(
CurvedAnimation(
parent: controller,
curve: Interval(
0.0,
0.7,
curve: Curves.decelerate,
)),
),
super(key: key);
final AnimationController controller;
final Animation<double> scale;
final Animation<double> translation;
final Animation<double> rotation;
build(context) {
return AnimatedBuilder(
animation: controller,
builder: (context, builder) {
return Transform.rotate(
angle: radians(rotation.value),
child: Stack(alignment: Alignment.center, children: [
_buildButton(0, _close,
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.chartBar),
_buildButton(60, _close,
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.clipboard),
_buildButton(120, _close,
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.chartBar),
_buildButton(180, _close,
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.book),
_buildButton(240, _close,
color: Color(0xFF29B6F6),
icon: FontAwesomeIcons.arrowsAltV),
_buildButton(300, _navigate,
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.phoneAlt),
_buildButton(360, _close,
color: Color(0xFF29B6F6),
icon: FontAwesomeIcons.compressAlt),
Transform.scale(
scale: scale.value - 1.5,
child: FloatingActionButton(
child: Icon(FontAwesomeIcons.timesCircle),
onPressed: _close,
backgroundColor: Color(0xFF29B6F6)),
),
Transform.scale(
scale: scale.value,
child: FloatingActionButton(
child: Icon(FontAwesomeIcons.solidDotCircle),
onPressed: _open,
backgroundColor: Color(0xFF29B6F6)),
),
]));
});
}
_buildButton(double angle, Function callback, {Color color, IconData icon}) {
final double rad = radians(angle);
return Transform(
transform: Matrix4.identity()
..translate(
(translation.value) * cos(rad), (translation.value) * sin(rad)),
child: FloatingActionButton(
child: Icon(icon), backgroundColor: color, onPressed: callback));
}
_open() {
controller.forward();
}
_close() {
controller.reverse();
}
_navigate(BuildContext context) {
Navigator.push(
context, new MaterialPageRoute(builder: (context) => Assistance()));
}
}
I think it is because you lose your context argument when calling _buildButton.
/// By writing your Function parameter like this you will pass the
/// BuildContext parameter needed.
_buildButton(
300,
() => _navigate(context),
color: Color(0xFF29B6F6),
icon: FontAwesomeIcons.phoneAlt
),
You need to pass BuildContext to the _navigate function when you reference it. You could do this with an anonymous function. _buildButton(300,(context) => _navigate(context), ...
It doesn't work because you didn't give the context parameter of the function's method. I guess so
_buildButton(300, _navigate(context),
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.phoneAlt),
Try out below example for more idea:-
_buildButton(300, _navigate(context), // Added Context here,It will contains context of build function
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.phoneAlt),
_navigate(BuildContext context) {
Navigator.push(
context, new MaterialPageRoute(builder: (context) => Assistance()));
}
When calling your function _buildButton you must wrap _navigate function into another function, since it need your current context to work
Try this
_buildButton(300, () {
_navigate(context);
}, color: Color(0xFF29B6F6), icon: FontAwesomeIcons.phoneAlt),
Related
I'm a beginner with Flutter, I have create a circle menu with Flutter, I got 6 buttons inside it and i want to go to different page depend of what button have been clicked. I know how to navigate to another page, but the problem is I can only use 1 action ("close action"). Maybe I can put an argument on the _buildbutton for the onPressed ?
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:vector_math/vector_math.dart' show radians;
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Color(0xFFB3E5FC),
body: SizedBox.expand(child: RadialMenu())),
);
}
}
class RadialMenu extends StatefulWidget {
createState() => _RadialMenuState();
}
class _RadialMenuState extends State<RadialMenu>
with SingleTickerProviderStateMixin {
AnimationController controller;
void initState() {
super.initState();
controller =
AnimationController(duration: Duration(milliseconds: 900), vsync: this);
}
Widget build(BuildContext context) {
return RadialAnimation(controller: controller);
}
}
class RadialAnimation extends StatelessWidget {
RadialAnimation({Key key, this.controller})
: scale = Tween<double>(
begin: 1.5,
end: 0.0,
).animate(
CurvedAnimation(parent: controller, curve: Curves.fastOutSlowIn),
),
translation = Tween<double>(
begin: 0.0,
end: 100.0,
).animate(
CurvedAnimation(parent: controller, curve: Curves.linear),
),
rotation = Tween<double>(begin: 0.0, end: 360.0).animate(
CurvedAnimation(
parent: controller,
curve: Interval(
0.0,
0.7,
curve: Curves.decelerate,
)),
),
super(key: key);
final AnimationController controller;
final Animation<double> scale;
final Animation<double> translation;
final Animation<double> rotation;
build(context) {
return AnimatedBuilder(
animation: controller,
builder: (context, builder) {
return Transform.rotate(
angle: radians(rotation.value),
child: Stack(alignment: Alignment.center, children: [
_buildButton(0,
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.chartBar),
_buildButton(60,
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.clipboard),
_buildButton(120,
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.chartBar),
_buildButton(180,
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.book),
_buildButton(240,
color: Color(0xFF29B6F6),
icon: FontAwesomeIcons.arrowsAltV),
_buildButton(300,
color: Color(0xFF29B6F6), icon: FontAwesomeIcons.phoneAlt),
_buildButton(360,
color: Color(0xFF29B6F6),
icon: FontAwesomeIcons.compressAlt),
Transform.scale(
scale: scale.value - 1.5,
child: FloatingActionButton(
child: Icon(FontAwesomeIcons.timesCircle),
onPressed: _close,
backgroundColor: Color(0xFF29B6F6)),
),
Transform.scale(
scale: scale.value,
child: FloatingActionButton(
child: Icon(FontAwesomeIcons.solidDotCircle),
onPressed: _open,
backgroundColor: Color(0xFF29B6F6)),
),
]));
});
}
_buildButton(double angle, {Color color, IconData icon}) {
final double rad = radians(angle);
return Transform(
transform: Matrix4.identity()
..translate(
(translation.value) * cos(rad), (translation.value) * sin(rad)),
child: FloatingActionButton(
child: Icon(icon), backgroundColor: color, onPressed: _close));
}
_open() {
controller.forward();
}
_close() {
controller.reverse();
}
}
In your _buildButton you can an action callback like this
_buildButton(double angle, Function callback, {Color color, IconData icon}) {
// ...
}
Then by building a button you can either pass _open or _close
I have an example of a FloatingActionButton working multiple but I don't know how to add it onPressed to it.
I found on the form of the following topic:
https://stackoverflow.com/a/46480722/14451514
In the example there are three icons I need to know how I can onPressed it how I do that?
import 'package:flutter/material.dart';
import 'dart:math' as math;
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
State createState() => new MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
AnimationController _controller;
static const List<IconData> icons = const [ Icons.sms, Icons.mail, Icons.phone ];
#override
void initState() {
_controller = new AnimationController(
vsync: this,
duration: const Duration(milliseconds: 500),
);
}
Widget build(BuildContext context) {
Color backgroundColor = Theme.of(context).cardColor;
Color foregroundColor = Theme.of(context).accentColor;
return new Scaffold(
appBar: new AppBar(title: new Text('Speed Dial Example')),
floatingActionButton: new Column(
mainAxisSize: MainAxisSize.min,
children: new List.generate(icons.length, (int index) {
Widget child = new Container(
height: 70.0,
width: 56.0,
alignment: FractionalOffset.topCenter,
child: new ScaleTransition(
scale: new CurvedAnimation(
parent: _controller,
curve: new Interval(
0.0,
1.0 - index / icons.length / 2.0,
curve: Curves.easeOut
),
),
child: new FloatingActionButton(
heroTag: null,
backgroundColor: backgroundColor,
mini: true,
child: new Icon(icons[index], color: foregroundColor),
onPressed: () {},
),
),
);
return child;
}).toList()..add(
new FloatingActionButton(
heroTag: null,
child: new AnimatedBuilder(
animation: _controller,
builder: (BuildContext context, Widget child) {
return new Transform(
transform: new Matrix4.rotationZ(_controller.value * 0.5 * math.pi),
alignment: FractionalOffset.center,
child: new Icon(_controller.isDismissed ? Icons.share : Icons.close),
);
},
),
onPressed: () {
if (_controller.isDismissed) {
_controller.forward();
} else {
_controller.reverse();
}
},
),
),
),
);
}
}
If anyone knows the solution to that problem please help me
I would suggest you to add a FAB Onpress button, use this github program.
Speed Dail Floating Action Bar
https://github.com/tiagojencmartins/unicornspeeddial
A List (Array) of functions can help you here, you have an index of the current item just get the function from List by index and call it onPress.
import 'package:flutter/material.dart';
import 'dart:math' as math;
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
State createState() => new MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
AnimationController _controller;
static const List<IconData> icons = const [
Icons.sms,
Icons.mail,
Icons.phone
];
static method1() {
print('method 1');
}
static method2() {
print('method 2');
}
static method3() {
print('method 3');
}
List<Function> methods = [method1, method2, method3];
#override
void initState() {
_controller = new AnimationController(
vsync: this,
duration: const Duration(milliseconds: 500),
);
}
Widget build(BuildContext context) {
Color backgroundColor = Theme.of(context).cardColor;
Color foregroundColor = Theme.of(context).accentColor;
return new Scaffold(
appBar: new AppBar(title: new Text('Speed Dial Example')),
floatingActionButton: new Column(
mainAxisSize: MainAxisSize.min,
children: new List.generate(icons.length, (int index) {
Widget child = new Container(
height: 70.0,
width: 56.0,
alignment: FractionalOffset.topCenter,
child: new ScaleTransition(
scale: new CurvedAnimation(
parent: _controller,
curve: new Interval(0.0, 1.0 - index / icons.length / 2.0,
curve: Curves.easeOut),
),
child: new FloatingActionButton(
heroTag: null,
backgroundColor: backgroundColor,
mini: true,
child: new Icon(icons[index], color: foregroundColor),
onPressed: () {
methods[index]();
},
),
),
);
return child;
}).toList()
..add(
new FloatingActionButton(
heroTag: null,
child: new AnimatedBuilder(
animation: _controller,
builder: (BuildContext context, Widget child) {
return new Transform(
transform: new Matrix4.rotationZ(
_controller.value * 0.5 * math.pi),
alignment: FractionalOffset.center,
child: new Icon(
_controller.isDismissed ? Icons.share : Icons.close),
);
},
),
onPressed: () {
if (_controller.isDismissed) {
_controller.forward();
} else {
_controller.reverse();
}
},
),
),
),
);
}
}
try this out
You need to extend your IconData list to a model that contains Function. It will look something like this:
class NewModel {
IconData iconData;
Function func;
}
And then:
static const List<NewModel> iconsWithFunc =
[
/* Your Items with OnPressed Functions */
];
After that you can use it easily:
child: new FloatingActionButton(
heroTag: null,
backgroundColor: backgroundColor,
mini: true,
child: new Icon(iconsWithFunc[index].iconData, color: foregroundColor),
// Use it in here.
onPressed: iconsWithFunc[index].func,
),
I am not unerstanding why the Provider is not being accepted here.
My main.dart looks like this.
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ChangeNotifierProvider<ContentDS>(
builder: (_) => ContentDS(),
child: Content(),
)
);
}
}
Provider works perfectly in Content Class.
Now I move from Content to Content Details using this code
Navigator.of(ctx).push(MaterialPageRoute(
builder: (context) =>
ContentDetails(viewedList: listElement),
))
In Content Details, I am just trying to access the Provider again
final ds = Provider.of<ContentDS>(context);
But this gives me the following error
Error: Could not find the correct Provider above this ContentDetails Widget
To fix, please:
Ensure the Provider is an ancestor to this
ContentDetails Widget * Provide types to Provider *
Provide types to Consumer * Provide types to
Provider.of() * Always use package imports. Ex: import
'package:my_app/my_code.dart'; * Ensure the correctcontext` is
being used.
Content-Details code
class ContentDetails extends StatefulWidget {
ToDoList viewedList;
ContentDetails({this.viewedList});
#override
_ContentDetailsState createState() => _ContentDetailsState();
}
class _ContentDetailsState extends State<ContentDetails> with SingleTickerProviderStateMixin{
bool isOpened = false;
AnimationController _animationController;
Animation<Color> _buttonColor;
Animation<double> _animateIcon;
Animation<double> _translateButton;
Curve _curve = Curves.easeOut;
double _fabHeight = 56.0;
initState() {
_animationController =
AnimationController(vsync: this, duration: Duration(milliseconds: 500))
..addListener(() {
setState(() {});
});
_animateIcon =
Tween<double>(begin: 0.0, end: 1.0).animate(_animationController);
_buttonColor = ColorTween(
begin: Colors.blue,
end: Colors.red,
).animate(CurvedAnimation(
parent: _animationController,
curve: Interval(
0.00,
1.00,
curve: Curves.linear,
),
));
_translateButton = Tween<double>(
begin: _fabHeight,
end: -14.0,
).animate(CurvedAnimation(
parent: _animationController,
curve: Interval(
0.0,
0.75,
curve: _curve,
),
));
super.initState();
}
#override
dispose() {
_animationController.dispose();
super.dispose();
}
animate() {
if (!isOpened) {
_animationController.forward();
} else {
_animationController.reverse();
}
isOpened = !isOpened;
}
#override
Widget build(BuildContext context) {
final ds = Provider.of<ContentDS>(context);
print(" ds.count ---> " + ds.count.toString());
if (widget.viewedList != null){
debugPrint(" widget.viewedList.primaryID ---> " + widget.viewedList.primaryID);
}else{
debugPrint(" It is null");
}
return
Hero(
tag: (widget.viewedList != null) ? widget.viewedList.primaryID : 'Hero',
child: Scaffold(
appBar: new AppBar(
backgroundColor: ListStatusHelper.getBgGenericColor(widget.viewedList?.status ?? ListStatus.NONE),
title: Text('${getListTitle()}'),
elevation: 0.0,
),
floatingActionButton: Wrap(
direction: Axis.vertical,
children: <Widget>[
transformWorks(edit(), 3),
transformWorks(save(), 2),
transformWorks(inbox(),1),
toggleButton()
],
),
body: Container(
color: ListStatusHelper.getBgGenericColor(widget.viewedList?.status ?? ListStatus.NONE),
child: const Text("Once Provider is available, need to work on this section");
),
),
);
}
Widget transformWorks(Widget btn, int pos){
return Transform(
transform: Matrix4.translationValues(
0.0,
_translateButton.value * pos,
0.0,
),
child: btn,
);
}
Widget inbox() {
return Container(
child: FloatingActionButton(
heroTag: null,
onPressed: null,
tooltip: 'Inbox',
elevation: 0.0,
child: Icon(Icons.inbox),
),
);
}
Widget edit() {
return Container(
child: FloatingActionButton(
heroTag: null,
onPressed: null,
tooltip: 'Edit',
elevation: 0.0,
child: Icon(Icons.edit),
),
);
}
Widget save() {
return Container(
child: FloatingActionButton(
heroTag: null,
onPressed: null,
tooltip: 'Save',
elevation: 0.0,
child: Icon(Icons.save),
),
);
}
Widget toggleButton(){
return FloatingActionButton(
heroTag: null,
backgroundColor: _buttonColor.value,
onPressed: animate,
tooltip: 'Toggle',
child: AnimatedIcon(
icon: AnimatedIcons.menu_close,
progress: _animateIcon,
),
);
}
String getListTitle() {
if (widget.viewedList != null) {
return widget.viewedList.listTitle;
} else {
return 'New List';
}
}
}
I am an iOS developer who is trying to learn flutter, and I thought that Provider should be available to all classes that belong within a navigational flow, without utilising any DI.
Help me realise what am I missing. How should Provider be used in case of navigational flows such as aforementioned cases.
Thanks in advance
Move ChangeNotifier above MyApp:
void main() {
runApp(ChangeNotifierProvider(
builder: (context) => ContentDS(),
child: MyApp()));
}
When performing navigation using Navigator.of(context) the route you push becomes part of the widget tree of your MaterialApp via its internal default Navigator. However, that route does not become a child of ChangeNotifierProvider but of the MaterialApp.
You should make the provider an ancestor of your MaterialApp.
I'm new in flutter, I need to create an interface like this
I've created a circular button in this way:
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => _buttonCallBack(),
child: ClipOval(
child: FractionallySizedBox(
heightFactor : 0.4,
widthFactor : 0.6,
child : Container(
color: Colors.lightGreen,
child : Center(
child: Text(
"Start",
style: new TextStyle(fontSize: 36.0),
)
)
)
),
),
);
But now I don't how to show buttons around the circle. Anyone has any ideas ?
If you're trying a circular menu you can follow this :
Add vector_math: ^2.0.8 and font_awesome_flutter: 8.4.0 to pubspec.yaml
Here is the full source of the example :
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:vector_math/vector_math.dart' show radians, Vector3;
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FlutterBase',
home: Scaffold(
body: SizedBox.expand(child: RadialMenu())
)
);
}
}
class RadialMenu extends StatefulWidget {
createState() => _RadialMenuState();
}
class _RadialMenuState extends State<RadialMenu> with SingleTickerProviderStateMixin {
AnimationController controller;
#override
void initState() {
super.initState();
controller = AnimationController(duration: Duration(milliseconds: 900), vsync: this);
// ..addListener(() => setState(() {}));
}
#override
Widget build(BuildContext context) {
return RadialAnimation(controller: controller);
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
}
class RadialAnimation extends StatelessWidget {
RadialAnimation({ Key key, this.controller }) :
translation = Tween<double>(
begin: 0.0,
end: 100.0,
).animate(
CurvedAnimation(
parent: controller,
curve: Curves.elasticOut
),
),
scale = Tween<double>(
begin: 1.5,
end: 0.0,
).animate(
CurvedAnimation(
parent: controller,
curve: Curves.fastOutSlowIn
),
),
rotation = Tween<double>(
begin: 0.0,
end: 360.0,
).animate(
CurvedAnimation(
parent: controller,
curve: Interval(
0.0, 0.7,
curve: Curves.decelerate,
),
),
),
super(key: key);
final AnimationController controller;
final Animation<double> rotation;
final Animation<double> translation;
final Animation<double> scale;
#override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: controller,
builder: (context, widget) {
return Transform.rotate(
angle: radians(rotation.value),
child: Stack(
alignment: Alignment.center,
children: <Widget>[
_buildButton(0, color: Colors.red, icon: FontAwesomeIcons.thumbtack),
_buildButton(45, color: Colors.green, icon:FontAwesomeIcons.sprayCan),
_buildButton(90, color: Colors.orange, icon: FontAwesomeIcons.fire),
_buildButton(135, color: Colors.blue, icon:FontAwesomeIcons.kiwiBird),
_buildButton(180, color: Colors.black, icon:FontAwesomeIcons.cat),
_buildButton(225, color: Colors.indigo, icon:FontAwesomeIcons.paw),
_buildButton(270, color: Colors.pink, icon: FontAwesomeIcons.bong),
_buildButton(315, color: Colors.yellow, icon:FontAwesomeIcons.bolt),
Transform.scale(
scale: scale.value - 1,
child: FloatingActionButton(child: Icon(FontAwesomeIcons.timesCircle), onPressed: _close, backgroundColor: Colors.red),
),
Transform.scale(
scale: scale.value,
child: FloatingActionButton(child: Icon(FontAwesomeIcons.solidDotCircle), onPressed: _open),
)
])
);
});
}
_open() {
controller.forward();
}
_close() {
controller.reverse();
}
_buildButton(double angle, { Color color, IconData icon }) {
final double rad = radians(angle);
return Transform(
transform: Matrix4.identity()..translate(
(translation.value) * cos(rad),
(translation.value) * sin(rad)
),
child: FloatingActionButton(
child: Icon(icon), backgroundColor: color, onPressed: _close, elevation: 0)
);
}
}
is any solution to make drag and drop dialogs in flutter? for example after showing dialog in center of screen i would like to drag it to top of screen to make fullscreen dialog over current cover, for example this code is simple implementation to show dialog and i'm not sure, how can i do that
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(title: 'Flutter Demo', theme: ThemeData(), home: Page());
}
}
class Page extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton.icon(
onPressed: () {
showDialog(
context: context,
builder: (_) => FunkyOverlay(),
);
},
icon: Icon(Icons.message),
label: Text("PopUp!")),
),
);
}
}
class FunkyOverlay extends StatefulWidget {
#override
State<StatefulWidget> createState() => FunkyOverlayState();
}
class FunkyOverlayState extends State<FunkyOverlay>
with SingleTickerProviderStateMixin {
AnimationController controller;
Animation<double> scaleAnimation;
#override
void initState() {
super.initState();
controller =
AnimationController(vsync: this, duration: Duration(milliseconds: 450));
scaleAnimation =
CurvedAnimation(parent: controller, curve: Curves.elasticInOut);
controller.addListener(() {
setState(() {});
});
controller.forward();
}
#override
Widget build(BuildContext context) {
return Center(
child: Material(
color: Colors.transparent,
child: ScaleTransition(
scale: scaleAnimation,
child: Container(
decoration: ShapeDecoration(
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0))),
child: Padding(
padding: const EdgeInsets.all(50.0),
child: Text("Well hello there!"),
),
),
),
),
);
}
}
This is one way to do it ,
import 'package:flutter/material.dart';
main() {
runApp(MaterialApp(
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: App(),
));
}
class App extends StatefulWidget {
#override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.open_in_new),
onPressed: () {
showGeneralDialog(
context: context,
barrierDismissible: true,
barrierLabel: "hi",
barrierColor: Colors.black.withOpacity(0.2),
transitionDuration: Duration(milliseconds: 500),
pageBuilder: (context, pAnim, sAnim) {
return SafeArea(child: FloatingDialog());
},
transitionBuilder: (context, pAnim, sAnim, child) {
if (pAnim.status == AnimationStatus.reverse) {
return FadeTransition(
opacity: Tween(begin: 0.0, end: 0.0).animate(pAnim),
child: child,
);
} else {
return FadeTransition(
opacity: pAnim,
child: child,
);
}
},
);
},
),
);
}
}
class FloatingDialog extends StatefulWidget {
#override
_FloatingDialogState createState() => _FloatingDialogState();
}
class _FloatingDialogState extends State<FloatingDialog>
with TickerProviderStateMixin {
double _dragStartYPosition;
double _dialogYOffset;
Widget myContents = MyScaffold();
AnimationController _returnBackController;
Animation<double> _dialogAnimation;
#override
void initState() {
super.initState();
_dialogYOffset = 0.0;
_returnBackController =
AnimationController(vsync: this, duration: Duration(milliseconds: 1300))
..addListener(() {
setState(() {
_dialogYOffset = _dialogAnimation.value;
print(_dialogYOffset);
});
});
}
#override
void dispose() {
_returnBackController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(
top: 100.0,
bottom: 10.0,
left: 10.0,
right: 10.0,
),
child: Transform.translate(
offset: Offset(0.0, _dialogYOffset),
child: Column(
children: <Widget>[
Icon(
Icons.keyboard_arrow_up,
color: Colors.white,
),
Expanded(
child: GestureDetector(
onVerticalDragStart: (dragStartDetails) {
_dragStartYPosition = dragStartDetails.globalPosition.dy;
print(dragStartDetails.globalPosition);
},
onVerticalDragUpdate: (dragUpdateDetails) {
setState(() {
_dialogYOffset = (dragUpdateDetails.globalPosition.dy) -
_dragStartYPosition;
});
print(_dialogYOffset);
if (_dialogYOffset < -90.0) {
Navigator.of(context).pop();
Navigator.of(context).push(
PageRouteBuilder(
pageBuilder: (context, pAnim, sAnim) => myContents,
transitionDuration: Duration(milliseconds: 500),
transitionsBuilder: (context, pAnim, sAnim, child) {
if (pAnim.status == AnimationStatus.forward) {
return ScaleTransition(
scale: Tween(begin: 0.8, end: 1.0).animate(
CurvedAnimation(
parent: pAnim,
curve: Curves.elasticOut)),
child: child,
);
} else {
return FadeTransition(
opacity: pAnim,
child: child,
);
}
}),
);
}
},
onVerticalDragEnd: (dragEndDetails) {
_dialogAnimation = Tween(begin: _dialogYOffset, end: 0.0)
.animate(CurvedAnimation(
parent: _returnBackController,
curve: Curves.elasticOut));
_returnBackController.forward(from: _dialogYOffset);
_returnBackController.forward(from: 0.0);
},
child: myContents,
),
),
],
),
),
);
}
}
class MyScaffold extends StatelessWidget {
const MyScaffold({
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Channels"),
),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.of(context).pop();
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => Scaffold(
appBar: AppBar(),
body: Placeholder(),
),
),
);
},
),
),
);
}
}
Output:
You can try this.
void main() => runApp(MaterialApp(home: HomePage()));
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _shown = false;
double _topOffset = 20, _dialogHeight = 400;
Duration _duration = Duration(milliseconds: 400);
Offset _offset, _initialOffset;
#override
void didChangeDependencies() {
super.didChangeDependencies();
var size = MediaQuery.of(context).size;
_offset = Offset(size.width, (size.height - _dialogHeight) / 2);
_initialOffset = _offset;
}
#override
Widget build(BuildContext context) {
var appBarColor = Colors.blue[800];
return Scaffold(
floatingActionButton: FloatingActionButton(onPressed: () => setState(() => _shown = !_shown)),
body: SizedBox.expand(
child: Stack(
children: <Widget>[
Container(
color: appBarColor,
child: SafeArea(
bottom: false,
child: Align(
child: Column(
children: <Widget>[
MyAppBar(
title: "Image",
color: appBarColor,
icon: Icons.home,
onPressed: () {},
),
Expanded(child: Image.asset("assets/images/landscape.jpeg", fit: BoxFit.cover)),
],
),
),
),
),
AnimatedOpacity(
opacity: _shown ? 1 : 0,
duration: _duration,
child: Material(
elevation: 8,
color: Colors.grey[900].withOpacity(0.5),
child: _shown
? GestureDetector(
onTap: () => setState(() => _shown = !_shown),
child: Container(color: Colors.transparent, child: SizedBox.expand()),
)
: SizedBox.shrink(),
),
),
// this shows our dialog
Positioned(
top: _offset.dy,
left: 10,
right: 10,
height: _shown ? null : 0,
child: AnimatedOpacity(
duration: _duration,
opacity: _shown ? 1 : 0,
child: GestureDetector(
onPanUpdate: (details) => setState(() => _offset += details.delta),
onPanEnd: (details) {
// when tap is lifted and current y position is less than set _offset, navigate to the next page
if (_offset.dy < _topOffset) {
Navigator.push(
context,
PageRouteBuilder(
pageBuilder: (context, anim1, anim2) => Screen2(),
transitionDuration: _duration,
transitionsBuilder: (context, anim1, anim2, child) {
bool isForward = anim1.status == AnimationStatus.forward;
Tween<double> tween = Tween(begin: isForward ? 0.9 : 0.5, end: 1);
return ScaleTransition(
scale: tween.animate(
CurvedAnimation(
parent: anim1,
curve: isForward ? Curves.bounceOut : Curves.easeOut,
),
),
child: child,
);
},
),
).then((_) {
_offset = _initialOffset;
});
}
// make the dialog come back to the original position
else {
Timer.periodic(Duration(milliseconds: 5), (timer) {
if (_offset.dy < _initialOffset.dy - _topOffset) {
_offset = Offset(_offset.dx, _offset.dy + 15);
setState(() {});
} else if (_offset.dy > _initialOffset.dy + _topOffset) {
_offset = Offset(_offset.dx, _offset.dy - 15);
setState(() {});
} else
timer.cancel();
});
}
},
child: Column(
children: <Widget>[
Icon(Icons.keyboard_arrow_up, color: Colors.white, size: 32),
Hero(
tag: "MyTag",
child: SizedBox(
height: _dialogHeight, // makes sure we don't exceed than our specified height
child: SingleChildScrollView(child: CommonWidget(appBar: MyAppBar(title: "FlutterLogo", color: Colors.orange))),
),
),
],
),
),
),
),
],
),
),
);
}
}
// this app bar is used in 1st and 2nd screen
class MyAppBar extends StatelessWidget {
final String title;
final Color color;
final IconData icon;
final VoidCallback onPressed;
const MyAppBar({Key key, #required this.title, #required this.color, this.icon, this.onPressed}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: kToolbarHeight,
color: color,
width: double.maxFinite,
alignment: Alignment.centerLeft,
child: Row(
children: <Widget>[
icon != null ? IconButton(icon: Icon(icon), onPressed: onPressed, color: Colors.white,) : SizedBox(width: 16),
Text(
title,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white),
),
],
),
);
}
}
// this is the one which is shown in both Dialog and Screen2
class CommonWidget extends StatelessWidget {
final bool isFullscreen;
final Widget appBar;
const CommonWidget({Key key, this.isFullscreen = false, this.appBar}) : super(key: key);
#override
Widget build(BuildContext context) {
var child = Container(
width: double.maxFinite,
color: Colors.blue,
child: FlutterLogo(size: 300, colors: Colors.orange),
);
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
appBar,
isFullscreen ? Expanded(child: child) : child,
],
);
}
}
class Screen2 extends StatelessWidget {
#override
Widget build(BuildContext context) {
var appBarColor = Colors.orange;
return Scaffold(
body: Container(
color: appBarColor,
child: SafeArea(
bottom: false,
child: CommonWidget(
isFullscreen: true,
appBar: MyAppBar(
title: "FlutterLogo",
color: appBarColor,
icon: Icons.arrow_back,
onPressed: () => Navigator.pop(context),
),
),
),
),
);
}
}