How do I use the offStage widget? - flutter

My first widget has a FlutterMap, As I navigate to another screen and come back for some reason the map will reload, so I want to hide it (maintain state), I tried using Visibility but it doesn't work and after some recommendation, I was told to use the OffStage widget but I have no clue on how to implement it.
Here is the logic, The first screen has a boolean check isVisible if it's true then the map will show on the screen, As I navigate away from the main screen then the boolean is set to false therefore the visibility is hidden. Again as I come back from the second screen the visibility is re set back to true hence showing the map. If I were to do the same thing using Offstage in place of Visibility how would I do it ?
class _MainScreenState extends State<MainScreen> {
bool isVisible= true;
Future testFunction(bool checkValue) async {
setState(() {
isVisible= checkValue;
});
#override
Widget build(BuildContext context) {
.....
Scaffold(
body: Container(
//change the margin
margin: EdgeInsets.fromLTRB(0, 0, 0, 300),
child:
Visibility(
visible: isVisible,
maintainAnimation: true,
maintainState: true,
child: (FlutterMap()
))
.........
GestureDetector(
onTap: () {
setState(() {
isVisible= !isVisible;
});
Navigator.push(
//send to search screen
context,
MaterialPageRoute(
builder: (context) => (SearchScreen(
testFunction: testFunction))));
The second page
class SearchScreen extends StatefulWidget {
final Function testFunction;
const SearchScreen({this.testFunction});
GestureDetector(
onTap: () {
Navigator.pop(
//send back data
context,
widget.testFunction(true));
},
child: Icon(Icons.arrow_back)),

If I were to do the same thing using Offstage in place of Visibility how would I do it?
Offstage works similar to Visibility, in the sense that they both have a boolean flag that you can use to toggle the action for each widget.
So to use an Offstage in place of a Visibility you can use:
Scaffold(
body: Container(
margin: EdgeInsets.fromLTRB(0, 0, 0, 300),
child: Offstage(
offstage: isVisible,
child: FlutterMap()
)

Related

Flutter open popup menu above list item

I am making a chat app in Flutter with Firestore but I am stumped with one of the requirement: Making a reaction menu appear above a chat dialog. I need that when the user long press on a chat text the reaction menu would appear above the current chat position. Something like Facebook Messenger app:
I have look around and found https://medium.com/#duytq94/facebook-reactions-with-flutter-9019ce8b95b8 but it seems it is too much for just a simple function (making a popup menu appear above a list tile and don't need the animation). I also found this package: https://pub.dev/packages/flutter_reaction_button, but it does not allow to wrap the widget around another to open up the reacton menu. Is there a simple way that I can archive this? I have looked into PopupMenuButton but it only allows onPressed and not long press.
You can use Overlay widget. I make a simple example for you.
import 'package:flutter/material.dart';
class Temp extends StatefulWidget {
#override
_TempState createState() => _TempState();
}
class _TempState extends State<Temp> {
GlobalKey floatingKey = LabeledGlobalKey("Floating");
bool isFloatingOpen = false;
OverlayEntry floating;
OverlayEntry createFloating() {
RenderBox renderBox = floatingKey.currentContext.findRenderObject();
Offset offset = renderBox.localToGlobal(Offset.zero);
return OverlayEntry(
builder: (context) {
return Positioned(
left: offset.dx,
width: renderBox.size.width,
top: offset.dy - 50,
child: Material(
elevation: 20,
child: Container(
height: 50,
color: Colors.blue,
child: Text("I'm floating overlay")
)
)
);
}
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
key: floatingKey,
color: Colors.red,
onPressed: (){
setState(() {
if(isFloatingOpen) floating.remove();
else {
floating = createFloating();
Overlay.of(context).insert(floating);
}
isFloatingOpen = !isFloatingOpen;
});
},
)
),
);
}
}

Flutter - How to flip the previous card back using FlipCard

After days of search I'm getting help.
I work on a flutter application.
Context:
A grid view feeded with Json
-childs : GridTile with Flipcard in (https://pub.dev/packages/flip_card)
-On tap on GridTile there is a callback to get the selected Item and an animation because of the flipcard onTap
What I would:
When an item is aleready selected (flipcard flipped so we show the back of the card),
And I selected another item of the grid te(so flipcard of this itme also flipped)
I would like to flip back the old selected item Flipcard without rebuild the tree because I would lost the state of the new selected item.
I tried many thing. For example I tried to use GlobalKey on GridTiles to interract with after build but currentState is always null when I want to interact with.
I wonder what is the good practice in this case ?
I hope I was clear :) (I'm french)
Thank you the community!
.
Something to know...
It is possible to interract with the flipcard (child of gridtile) like this
(GlobalKey)
GlobalKey<FlipCardState> cardKey = GlobalKey<FlipCardState>();
#override
Widget build(BuildContext context) {
return FlipCard(
key: cardKey,
flipOnTouch: false,
front: Container(
child: RaisedButton(
onPressed: () => cardKey.currentState.toggleCard(),
child: Text('Toggle'),
),
),
back: Container(
child: Text('Back'),
),
);
}
I'm not sure if I understood your question, but here is an example of how you could use a GridView with FlipCards:
var cardKeys = Map<int, GlobalKey<FlipCardState>>();
GlobalKey<FlipCardState> lastFlipped;
Widget _buildFlipCard(String text, Color color, int index) {
return SizedBox(
height: 120.0,
child: Card(
color: color,
child: Center(
child:
Text(text, style: TextStyle(color: Colors.white, fontSize: 20.0)),
),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("FlipCards")),
body: GridView.builder(
itemCount: 20,
itemBuilder: (context, index) {
cardKeys.putIfAbsent(index, () => GlobalKey<FlipCardState>());
GlobalKey<FlipCardState> thisCard = cardKeys[index];
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FlipCardWithKeepAlive(
child: FlipCard(
flipOnTouch: false,
key: thisCard,
front: _buildFlipCard("$index", Colors.blue, index),
back: _buildFlipCard("$index", Colors.green, index),
onFlip: () {
if (lastFlipped != thisCard) {
lastFlipped?.currentState?.toggleCard();
lastFlipped = thisCard;
}
},
),
),
RaisedButton(
child: Text("Flip Card"),
onPressed: () => cardKeys[index].currentState.toggleCard(),
)
],
);
},
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
),
);
}
class FlipCardWithKeepAlive extends StatefulWidget {
final FlipCard child;
FlipCardWithKeepAlive({Key key, this.child}) : super(key: key);
#override
State<StatefulWidget> createState() => FlipCardWithKeepAliveState();
}
class FlipCardWithKeepAliveState extends State<FlipCardWithKeepAlive>
with AutomaticKeepAliveClientMixin {
#override
Widget build(BuildContext context) {
super.build(context);
return widget.child;
}
#override
bool get wantKeepAlive => true;
}
You need to use a different key for each element of the list, I used a Map in this case.
I also wrapped the FlipCard with a custom FlipCardWithKeepAlive stateful widget that uses AutomaticKeepAliveClientMixin to keep alive the FlipCard while scrolling.
Edit: I updated the code so when you flip one card, the previous card flipped gets flipped back. Basically you need to save the last flipped card and when a new one is flipped, flip the last one and put the new one as last flipped.
The code will make both cards flip at the same time, if you want one card to wait the other use onFlipDone() instead of onFlip(), like this:
onFlipDone: (isFront) {
bool isFlipped = !isFront;
if (isFlipped && lastFlipped != thisCard) {
lastFlipped?.currentState?.toggleCard();
lastFlipped = thisCard;
}
}

modalBottomSheet is overlapped up by the keyboard

It's written here That
/// The scaffold will expand to fill the available space. That usually
/// means that it will occupy its entire window or device screen. When
/// the device's keyboard appears the Scaffold's ancestor [MediaQuery]
/// widget's [MediaQueryData.viewInsets] changes and the Scaffold will
/// be rebuilt. By default the scaffold's [body] is resized to make
/// room for the keyboard.
According to this if there is a TextField at the bottom, the Scaffold will resize itself and it does happen. But when I put a TextField inside a modalBottomSheet it doesn't get pushed up by the keyboard. The Keyboard overlaps the modalBottomSheet (with the TextField). If the Scaffold itself gets resized how modalBottomSheet stays at its place? And resizeToAvoidBottomInsethas no effect on modalBottomSheet.
Here is the sample code.
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
showModalBottomSheet(
context: context, builder: (context) => ShowSheet());
},
),
);
}
}
class ShowSheet extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
height: 200,
child: TextField(
autofocus: true,
),
);
}
}
I apologize if this question is dumb but I didn't understand this.
I still don't know the reason may be because modalBottomSheet is using PopupRoute so it's a different route not sure. Anyway, here I found the solution I just needed to put some bottom viewInsets padding.
Widget build(BuildContext context) {
return Padding(
padding:
EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: Container(
color: Colors.blue,
height: 200,
child: TextField(
autofocus: true,
),
),
);
}
Also I needed to set isScrollControlled: true, of showModalBottomSheet()

Refresh widget or page in Flutter without ListView et al

I want refresh my page without having a scrollable content, i.e. without having a ListView et al.
When I want use RefreshIndicator, the documentation says it needs a scrollable widget like ListView.
But if I want to refresh and want to use the refresh animation of RefreshIndicator without using a ListView, GridView or any other scorllable widget, how can i do that?
You can simply wrap your content in a SingleChildScrollView, which will allow you to use a RefreshIndicator. In order to make the pull down to refresh interaction work, you will have to use AlwaysScrollableScrollPhysics as your content will most likely not cover more space than available without a scroll view:
RefreshIndicator(
onRefresh: () async {
// Handle refresh.
},
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: /* your content */,
),
);
You can just use GestureDetector, I have created a sample for you, but it's not perfect, you can customize it to your own needs, it just detects when you swipe from the top.
class Test extends StatefulWidget {
#override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
var refresh=false;
void refreshData(){
if(!refresh){
refresh=true;
print("Refreshing");
Future.delayed(Duration(seconds: 4),(){
refresh =false;
print("Refreshed");
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Test"),
centerTitle: true,
),
body: GestureDetector(
child: Container(
color: Colors.yellow,
height: double.infinity,
width: double.infinity,
child: Center(child: Text('TURN LIGHTS ON')),
),
onVerticalDragUpdate: (DragUpdateDetails details){
print("direction ${details.globalPosition.direction}");
print("distance ${details.globalPosition.distance}");
print("dy ${details.globalPosition.dy}");
if(details.globalPosition.direction < 1 && (details.globalPosition.dy >200 && details.globalPosition.dy < 250)){
refreshData();
}
},
));
}
}

Permanent Persistent Bottom sheet flutter

I want my bottom sheet to stay on the screen till I close it from a code. Normally the bottom sheet can be closed by pressing back button(device or appbar) or even just by a downward gesture. How can I disable that?
_scaffoldKey.currentState
.showBottomSheet<Null>((BuildContext context) {
final ThemeData themeData = Theme.of(context);
return new ControlBottom(
songName: songName,
url: url,
play: play,
pause: pause,
state: test,
themeData: themeData,
);
}).closed.whenComplete((){
});
Control botton is a different widget.
Scaffold now has a bottom sheet argument and this bottom sheet cannot be dismissed by swiping down the screen.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(....),
bottomSheet: Container(
child: Text('Hello World'),
),
);
}
Also you can use WillPopScope Widget to control pressing back button:
Widget _buildBottomSheet() {
return WillPopScope(
onWillPop: () {
**here you can handle back button pressing. Just leave it empty to disable back button**
},
child: **your bottom sheet**
)),
);
}
You can remove the appbar back button by providing an empty container in leading property.
AppBar(
leading: Container(),
);
But we don't have any control over device back button & bottomsheet will disappear on back pressed.
One of the many alternative approach could be using a stack with positioned & opacity widget
Example :
Stack(
children: <Widget>[
// your code here
Positioned(
left: 0.0,
right: 0.0,
bottom: 0.0,
child: Opacity(
opacity: _opacityLevel,
child: Card(
child: //Your Code Here,
),
),
),
// your code here
],
);
You can change _opacityLevel from 0.0 to 1.0 when a song is selected.
From what I can make out from your code is that you will be having a listView on top & music controls on the bottom. Make sure to add some Padding at the end of listView so that your last list item does not stay hidden behind your music controller card when you have scrolled all the way down.
If you want to further customize the look & feel of your music controller. You could use animationController or sizeAnimation to slide it from the bottom like a bottomSheet.
I hope this helps.
Add this parameters to showmodalbottomsheet,
isDismissible: false, enableDrag: false,
I wanted a bottomsheet that is draggable up and down, but does not close. So, first of all I created a function for my modalBottomSheet.
Future modalBottomSheetShow(BuildContext context) {
return showModalBottomSheet(
backgroundColor: Colors.transparent,
context: context,
builder: (context) => buildSheet(),
isDismissible: false,
elevation: 0,
);
}
Next, I used .whenComplete() method of showModalBottomSheet() to recursively call the modalBottomSheetShow() function.
Future modalBottomSheetShow(BuildContext context) {
return showModalBottomSheet(
backgroundColor: Colors.transparent,
context: context,
builder: (context) => buildSheet(),
isDismissible: false,
elevation: 0,
).whenComplete(() => modalBottomSheetShow(context));
}
Next, I simply call the modalBottomSheetShow() whenever I wanted a bottomsheet. It cannot be closed, until the recursion ends. Here is the entire code for reference:
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
static const idScreen = "HomePage";
#override
State<HomePage> createState() => _HomePageState();
}
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
modalBottomSheetShow(context);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: 0,
elevation: 0,
backgroundColor: Colors.black,
),
);
}
Widget buildSheet() {
return DraggableScrollableSheet(
initialChildSize: 0.6,
builder: (BuildContext context, ScrollController scrollController) {
return Container(
decoration: BoxDecoration(color: Colors.white, boxShadow: [
BoxShadow(
color: Color(0x6C000000),
spreadRadius: 5,
blurRadius: 20,
offset: Offset(0, 0),
)
]),
padding: EdgeInsets.all(16),
);
},
);
}
Future modalBottomSheetShow(BuildContext context) {
return showModalBottomSheet(
backgroundColor: Colors.transparent,
context: context,
builder: (context) => buildSheet(),
isDismissible: false,
elevation: 0,
).whenComplete(() => modalBottomSheetShow(context));
}
}