How to take screenshot of widget beyond the screen in flutter? - dart

I am using RepaintBoundary to take the screenshot of the current widget which is a listView. But it only captures the content which is visible on the screen at the time.
RepaintBoundary(
key: src,
child: ListView(padding: EdgeInsets.only(left: 10.0),
scrollDirection: Axis.horizontal,
children: <Widget>[
Align(
alignment: Alignment(-0.8, -0.2),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: listLabel(orientation),
)
),
Padding(padding: EdgeInsets.all(5.0)),
Align(
alignment: FractionalOffset(0.3, 0.5),
child: Container(
height: orientation == Orientation.portrait? 430.0: 430.0*0.7,
decoration: BoxDecoration(
border: Border(left: BorderSide(color: Colors.black))
),
//width: 300.0,
child:
Wrap(
direction: Axis.vertical,
//runSpacing: 10.0,
children: colWidget(orientation),
)
)
),
Padding(padding: EdgeInsets.all(5.0)),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: listLabel(orientation),
)
],
),
);
screenshot function:
Future screenshot() async {
RenderRepaintBoundary boundary = src.currentContext.findRenderObject();
ui.Image image = await boundary.toImage();
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
print(pngBytes);
final directory = (await getExternalStorageDirectory()).path;
File imgFile =new File('$directory/layout2.pdf');
imgFile.writeAsBytes(pngBytes);
}
Is there any way, so that I can capture the whole listView, i.e., not only the content which is not visible on the screen but the scrollable content also. Or maybe if the whole widget is too large to fit in a picture, it can be captured in multiple images.

I achieve the solution of this problem using this package: Screenshot, that takes a screenshot of the entire widget. It's easy and simple, follow the steps on the PubDev or GitHub and you can make it work.
OBS: To take a full screenshot of the widget make sure that your widget is fully scrollable, and not just a part of it.
(In my case, i had a ListView inside a Container, and the package doesn't take the screenshot of all ListView because i have many itens on it, SO i have wrap my Container inside a SingleChildScrollView and add the NeverScrollableScrollPhysics physics in the ListView and it works! :D).
Screenshot of my screen
More details in this issue

This made me curious whether it was possible so I made a quick mock-up that shows it does work. But please be aware that by doing this you're essentially intentionally breaking the things flutter does to optimize, so you really shouldn't use it beyond where you absolutely have to.
Anyways, here's the code:
import 'dart:math';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() => runApp(MyApp());
class UiImagePainter extends CustomPainter {
final ui.Image image;
UiImagePainter(this.image);
#override
void paint(ui.Canvas canvas, ui.Size size) {
// simple aspect fit for the image
var hr = size.height / image.height;
var wr = size.width / image.width;
double ratio;
double translateX;
double translateY;
if (hr < wr) {
ratio = hr;
translateX = (size.width - (ratio * image.width)) / 2;
translateY = 0.0;
} else {
ratio = wr;
translateX = 0.0;
translateY = (size.height - (ratio * image.height)) / 2;
}
canvas.translate(translateX, translateY);
canvas.scale(ratio, ratio);
canvas.drawImage(image, new Offset(0.0, 0.0), new Paint());
}
#override
bool shouldRepaint(UiImagePainter other) {
return other.image != image;
}
}
class UiImageDrawer extends StatelessWidget {
final ui.Image image;
const UiImageDrawer({Key key, this.image}) : super(key: key);
#override
Widget build(BuildContext context) {
return CustomPaint(
size: Size.infinite,
painter: UiImagePainter(image),
);
}
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
GlobalKey<OverRepaintBoundaryState> globalKey = GlobalKey();
ui.Image image;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: image == null
? Capturer(
overRepaintKey: globalKey,
)
: UiImageDrawer(image: image),
floatingActionButton: image == null
? FloatingActionButton(
child: Icon(Icons.camera),
onPressed: () async {
var renderObject = globalKey.currentContext.findRenderObject();
RenderRepaintBoundary boundary = renderObject;
ui.Image captureImage = await boundary.toImage();
setState(() => image = captureImage);
},
)
: FloatingActionButton(
onPressed: () => setState(() => image = null),
child: Icon(Icons.remove),
),
),
);
}
}
class Capturer extends StatelessWidget {
static final Random random = Random();
final GlobalKey<OverRepaintBoundaryState> overRepaintKey;
const Capturer({Key key, this.overRepaintKey}) : super(key: key);
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: OverRepaintBoundary(
key: overRepaintKey,
child: RepaintBoundary(
child: Column(
children: List.generate(
30,
(i) => Container(
color: Color.fromRGBO(random.nextInt(256), random.nextInt(256), random.nextInt(256), 1.0),
height: 100,
),
),
),
),
),
);
}
}
class OverRepaintBoundary extends StatefulWidget {
final Widget child;
const OverRepaintBoundary({Key key, this.child}) : super(key: key);
#override
OverRepaintBoundaryState createState() => OverRepaintBoundaryState();
}
class OverRepaintBoundaryState extends State<OverRepaintBoundary> {
#override
Widget build(BuildContext context) {
return widget.child;
}
}
What it's doing is making a scroll view that encapsulates the list (column), and making sure the repaintBoundary is around the column. With your code where you use a list, there's no way it can ever capture all the children as the list is essentially a repaintBoundary in and of itself.
Note in particular the 'overRepaintKey' and OverRepaintBoundary. You might be able to get away without using it by iterating through render children, but it makes it a lot easier.

There is a simple way
You need wrap SingleChildScrollView Widget to RepaintBoundary. just wrap your Scrollable widget (or his father) with SingleChildScrollView
SingleChildScrollView(
child: RepaintBoundary(
key: _globalKey
)
)

Related

Flutter custom clipper with stack not working correctly

I really interested with flutter, and currently I'm trying to create a custom clipper with clipPart widget. but it's seems not working correctly.
here is my code
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
title: "My App",
home: HomePage(),
debugShowCheckedModeBanner: false,
));
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Container(
alignment: Alignment.topCenter,
color: Colors.teal,
child: HomeScreenTop(),
)
],
),
);
}
}
class HomeScreenTop extends StatefulWidget {
#override
_HomeScreenTopState createState() => _HomeScreenTopState();
}
class _HomeScreenTopState extends State<HomeScreenTop> {
#override
Widget build(BuildContext context) {
return Stack(
textDirection: TextDirection.ltr,
children: <Widget>[
Align(
alignment: Alignment.topCenter,
child: WaveContainer(),
),
],
);
}
}
class WaveContainer extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ClipPath(
clipper: CustomShapeClipper(),
clipBehavior: Clip.antiAlias,
child: Container(
width: MediaQuery.of(context).size.width,
height: 400.0,
color: Colors.orange,
),
);
}
}
class CustomShapeClipper extends CustomClipper<Path> {
#override
getClip(Size size) {
print(size.height);
final Path path =Path();
path.lineTo(size.width / 2, size.height);
path.lineTo(size.width, 0);
path.close();
return path;
}
#override
bool shouldReclip(CustomClipper oldClipper) => true;
}
what I want to do is, create a triangle from top to bottom, as I know from the tutorial, Offset of x = 0 and y = 0 should be pointing to left-top corner of the page. So if create like this
path.lineTo(size.width / 2, size.height);
path.lineTo(size.width, 0);
the path should be drawing from left-top to middle-down to right-top and back to left-top
But what I've got when I try the code is like this
And, the stack is not working.. the triangle should isolated inside the container but why the custom clipper can exceed the bottom container??
I really confuse, Please help
Solved by change the emulator from Genymotion to iOS IphoneX emulator. Don't know why it show different behaviour between iOS and android, but I think iOS emulator is the right one..

How to make 'stacked card list view' in flutter?

I want to build ui similar to this link in flutter.
https://github.com/loopeer/CardStackView/blob/master/screenshot/screenshot1.gif
Key ideal features are followings.
Behave like list view, but cards should be stacked at the top of screen.
List can have infinite items. So old cards should be recycled to save memory.
I also want to set different size to each card.
First, I found some 'tinder' like ui like following and tried them.
https://blog.geekyants.com/tinder-swipe-in-flutter-7e4fc56021bc
However, users need to swipe each single card, that required user to swipe many times to browse list items.
And then I could somehow make a list view whose items are overlapped with next ones.
import 'package:flutter/material.dart';
class StackedList extends StatelessWidget {
List<ItemCard> cards = [];
StackedList() {
for (int i = 0; i < 20; i++) {
cards.add(ItemCard(i));
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('title')),
body: Container(
child: ListView.builder(
itemBuilder: (context, index) {
return Align(
alignment: Alignment.topCenter,
heightFactor: 0.8,
child: cards[index],
);
},
itemCount: cards.length,
),
),
);
}
}
class ItemCard extends StatelessWidget {
int index;
ItemCard(this.index);
#override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
boxShadow: [
BoxShadow(color: Colors.black, blurRadius: 20.0),
],
),
child: SizedBox.fromSize(
size: const Size(300, 400),
child: Card(
elevation: 5.0,
color: index % 2 == 0 ? Colors.blue : Colors.red,
child: Center(
child: Text(index.toString()),
),
),
),
);
}
}
However items don't stop at the top of screen, which is not exactly what I want.
I guess I can achieve this effect by customizing ScrollController or ScrollPhysics but I'm not sure where I should change.
You can achieve a similar behaviour with SliverPersistentHeader and a CustomScrollView, and you can wrap your cards in GestureDetector to modify their height by changing the value of SliverPersistentHeaderDelegate's maxExtent parameter. Here is a small app I wrote that achieves something that might look like what you are looking for:
import 'package:flutter/material.dart';
import 'dart:math' as math;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Stacked list example',
home: Scaffold(
appBar: AppBar(
title: Text("Stacked list example"),
backgroundColor: Colors.black,
),
body: StackedList()),
);
}
}
class StackedList extends StatelessWidget {
final List<Color> _colors = Colors.primaries;
static const _minHeight = 16.0;
static const _maxHeight = 120.0;
#override
Widget build(BuildContext context) => CustomScrollView(
slivers: _colors
.map(
(color) => StackedListChild(
minHeight: _minHeight,
maxHeight: _colors.indexOf(color) == _colors.length - 1
? MediaQuery.of(context).size.height
: _maxHeight,
pinned: true,
child: Container(
color: _colors.indexOf(color) == 0
? Colors.black
: _colors[_colors.indexOf(color) - 1],
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.vertical(
top: Radius.circular(_minHeight)),
color: color,
),
),
),
),
)
.toList(),
);
}
class StackedListChild extends StatelessWidget {
final double minHeight;
final double maxHeight;
final bool pinned;
final bool floating;
final Widget child;
SliverPersistentHeaderDelegate get _delegate => _StackedListDelegate(
minHeight: minHeight, maxHeight: maxHeight, child: child);
const StackedListChild({
Key key,
#required this.minHeight,
#required this.maxHeight,
#required this.child,
this.pinned = false,
this.floating = false,
}) : assert(child != null),
assert(minHeight != null),
assert(maxHeight != null),
assert(pinned != null),
assert(floating != null),
super(key: key);
#override
Widget build(BuildContext context) => SliverPersistentHeader(
key: key, pinned: pinned, floating: floating, delegate: _delegate);
}
class _StackedListDelegate extends SliverPersistentHeaderDelegate {
final double minHeight;
final double maxHeight;
final Widget child;
_StackedListDelegate({
#required this.minHeight,
#required this.maxHeight,
#required this.child,
});
#override
double get minExtent => minHeight;
#override
double get maxExtent => math.max(maxHeight, minHeight);
#override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
return new SizedBox.expand(child: child);
}
#override
bool shouldRebuild(_StackedListDelegate oldDelegate) {
return maxHeight != oldDelegate.maxHeight ||
minHeight != oldDelegate.minHeight ||
child != oldDelegate.child;
}
}
Here is how it looks like in action:
Stacked list example .gif
And here is a really good article about Flutter's slivers that might help you in this regard:
Slivers, demystified
Hope this helps you get in the right direction.

Flutter GestureDetector: How to pinch in/out or zoom in/out Text using two fingers?

I'm creating a text field like Text or RichText. And after that, I want to zoom in/out the size of text using pinching. For now, I tried implementing GestureDetector but it zooms in/out with one finger too. And it is really hard to aim pinching detection. Sometimes is freezing. I added a video that shows when after pinching it freezes and suddenly get bigger. The second video is with the case that image zoom in only when I tap on the text with one finger and move to up left corner. The ideal implementation is to detect pinch and zoom in/out all text area. And disable zooming when I use only one finger. Could you send me some hints, link or code how to solve or where to find the solution?
body: GestureDetector(
onScaleUpdate: (details) {
setState(() {
_textSize =
_initTextSize + (_initTextSize * (details.scale * .35));
});
},
onScaleEnd: (ScaleEndDetails details) {
setState(() {
_initTextSize = _textSize;
});
},
child: Center(
child: SizedBox(
height: _textSize,
child: FittedBox(
child: Text("Test"),
),
))),
In Stateful widget with these configuration
double _scaleFactor = 1.0;
double _baseScaleFactor = 1.0;
And use setState only on update, using the scaleFactor on textScaleFactor property of RichText.
Only one setState to rebuild widget and store the initial factor when scale starts
GestureDetector(
onScaleStart: (details) {
_baseScaleFactor = _scaleFactor;
},
onScaleUpdate: (details) {
setState(() {
_scaleFactor = _baseScaleFactor * details.scale;
});
},
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
color: Colors.red,
child: Center(
child: Text(
'Test',
textScaleFactor: _scaleFactor,
),
),
),
);
The height and width I put just to expand and simulate area of gesture detector.
Google software engineers Gary Qian and Chris Yang demonstrated this in their Google Developer Days talk. The video is viewable here:
Text in Flutter: Building a fancy chat bubble at GDD China
There code is similar to some of the other answers here, but they notably add a clamp so that it doesn't get too big or small.
Here is a summary of their scalable text bubble:
Because scaling still gets called even for a single finger touch, I added a check for scaleUpdateDetails.scale == 1.0. That means the UI won't be updated if there was no change in scale.
class Bubble extends StatefulWidget {
#override
_BubbleState createState() => _BubbleState();
}
class _BubbleState extends State<Bubble> {
double _fontSize = 20;
final double _baseFontSize = 20;
double _fontScale = 1;
double _baseFontScale = 1;
#override
Widget build(BuildContext context) {
return GestureDetector(
onScaleStart: (ScaleStartDetails scaleStartDetails) {
_baseFontScale = _fontScale;
},
onScaleUpdate: (ScaleUpdateDetails scaleUpdateDetails) {
// don't update the UI if the scale didn't change
if (scaleUpdateDetails.scale == 1.0) {
return;
}
setState(() {
_fontScale = (_baseFontScale * scaleUpdateDetails.scale).clamp(0.5, 5.0);
_fontSize = _fontScale * _baseFontSize;
});
},
child: ...
// descendant with a Text widget that uses the _fontSize
);
}
}
Notes:
Use a StatefulWidget so that you can store the current font size and scale at all times
Use two additional variables to remember the original font size and also the scale at the start of the pinch
Wrap the Text widget in a GestureDetector
Save the original scale in onScaleStart
Calculate the new font size onScaleUpdate
Use setState to rebuild the widget with the new size
Solution: Two finger zoom-in and zoom-out.
import 'package:flutter/material.dart';
import 'package:matrix_gesture_detector/matrix_gesture_detector.dart';
class TransformText extends StatefulWidget {
TransformText({Key key}) : super(key: key); // changed
#override
_TransformTextState createState() => _TransformTextState();
}
class _TransformTextState extends State<TransformText> {
double scale = 0.0;
#override
Widget build(BuildContext context) {
final ValueNotifier<Matrix4> notifier = ValueNotifier(Matrix4.identity());
return Scaffold(
appBar: AppBar(
title: Text('Single finger Rotate text'), // changed
),
body: Center(
child: MatrixGestureDetector(
onMatrixUpdate: (m, tm, sm, rm) {
notifier.value = m;
},
child: AnimatedBuilder(
animation: notifier,
builder: (ctx, child) {
return Transform(
transform: notifier.value,
child: Center(
child: Stack(
children: <Widget>[
Container(
color: Colors.red,
padding: EdgeInsets.all(10),
margin: EdgeInsets.only(top: 50),
child: Transform.scale(
scale:
1, // make this dynamic to change the scaling as in the basic demo
origin: Offset(0.0, 0.0),
child: Container(
height: 100,
child: Text(
"Two finger to zoom!!",
style:
TextStyle(fontSize: 26, color: Colors.white),
),
),
),
),
],
),
),
);
},
),
),
),
);
}
}
Full code. Hope it helps.
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final appTitle = 'Demo';
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: TransformText());
}
}
class TransformText extends StatefulWidget {
TransformText({Key key}) : super(key: key); // changed
#override
_TransformTextState createState() => _TransformTextState();
}
class _TransformTextState extends State<TransformText> {
double scale = 0.0;
double _scaleFactor = 1.0;
double _baseScaleFactor = 1.0;
double _savedVal = 1.0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GestureDetector Test'), // changed
),
body: Column(
children: <Widget>[
RaisedButton(
child: Text('get'),
onPressed: () {
_savedVal = _scaleFactor;
}),
RaisedButton(
child: Text('set'),
onPressed: () {
setState(() {
_scaleFactor = _savedVal;
});
}),
Expanded(
child: Center(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onScaleStart: (details) {
_baseScaleFactor = _scaleFactor;
},
onScaleUpdate: (details) {
setState(() {
_scaleFactor = _baseScaleFactor * details.scale;
});
},
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Center(
child: Text(
'Test',
textScaleFactor: _scaleFactor,
),
),
),
)),
),
],
),
);
}
}

Flutter - PopupMenu on long press

I'm making an image gallery and I need the user to be able to long-press an image to show a popup menu which will let him delete the image.
My code, so far:
return GestureDetector(
onLongPress: () {
showMenu(
items: <PopupMenuEntry>[
PopupMenuItem(
value: this._index,
child: Row(
children: <Widget>[
Icon(Icons.delete),
Text("Delete"),
],
),
)
],
context: context,
);
},
child: Image.memory(
this._asset.thumbData.buffer.asUint8List(),
fit: BoxFit.cover,
gaplessPlayback: true,
),
);
Which produces:
But also, I couldn't find out how to completely remove the image's widget when the longPress function is called. How to do so?
The OP and the First Answerer bypassed the original problem using PopupMenuButton, which worked fine in their case. But I think the more general question of how to position one's own menu and how to receive the user's response without using PopupMenuButton is worth answering, because sometimes we want a popup menu on a custom widget, and we want it to appear on some gestures other than a simple tap (e.g. the OP's original intention was to long-press).
I set out to make a simple app demonstrating the following:
Use a GestureDetector to capture long-press
Use the function showMenu() to display a popup menu, and position it near the finger's touch
How to receive the user's selection
(Bonus) How to make a PopupMenuEntry that represents multiple values (the oft-used PopupMenuItem can only represent a single value)
The result is, when you long-press on a big yellow area, a popup menu appears on which you can select +1 or -1, and the big number would increment or decrement accordingly:
Skip to the end for the entire body of code. Comments are sprinkled in there to explain what I am doing. Here are a few things to note:
showMenu()'s position parameter takes some effort to understand. It's a RelativeRect, which represents how a smaller rect is positioned inside a bigger rect. In our case, the bigger rect is the entire screen, the smaller rect is the area of touch. Flutter positions the popup menu according to these rules (in plain English):
if the smaller rect leans toward the left half of the bigger rect, the popup menu would align with the smaller rect's left edge
if the smaller rect leans toward the right half of the bigger rect, the popup menu would align with the smaller rect's right edge
if the smaller rect is in the middle, which edge wins depends on the language's text direction. Left edge wins if using English and other left-to-right languages, right edge wins otherwise.
It's always useful to reference PopupMenuButton's official implementation to see how it uses showMenu() to display the menu.
showMenu() returns a Future. Use Future.then() to register a callback to handle user selection. Another option is to use await.
Remember that PopupMenuEntry is a (subclass of) StatefulWidget. You can layout any number of sub-widgets inside it. This is how you represent multiple values in a PopupMenuEntry. If you want it to represent two values, just make it contain two buttons, however you want to lay them out.
To close the popup menu, use Navigator.pop(). Flutter treats popup menus like a smaller "page". When we display a popup menu, we are actually pushing a "page" to the navigator's stack. To close a popup menu, we pop it from the stack, thus completing the aforementioned Future.
Here is the full code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Popup Menu Usage',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Popup Menu Usage'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _count = 0;
var _tapPosition;
void _showCustomMenu() {
final RenderBox overlay = Overlay.of(context).context.findRenderObject();
showMenu(
context: context,
items: <PopupMenuEntry<int>>[PlusMinusEntry()],
position: RelativeRect.fromRect(
_tapPosition & const Size(40, 40), // smaller rect, the touch area
Offset.zero & overlay.size // Bigger rect, the entire screen
)
)
// This is how you handle user selection
.then<void>((int delta) {
// delta would be null if user taps on outside the popup menu
// (causing it to close without making selection)
if (delta == null) return;
setState(() {
_count = _count + delta;
});
});
// Another option:
//
// final delta = await showMenu(...);
//
// Then process `delta` however you want.
// Remember to make the surrounding function `async`, that is:
//
// void _showCustomMenu() async { ... }
}
void _storePosition(TapDownDetails details) {
_tapPosition = details.globalPosition;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GestureDetector(
// This does not give the tap position ...
onLongPress: _showCustomMenu,
// Have to remember it on tap-down.
onTapDown: _storePosition,
child: Container(
color: Colors.amberAccent,
padding: const EdgeInsets.all(100.0),
child: Text(
'$_count',
style: const TextStyle(
fontSize: 100, fontWeight: FontWeight.bold),
),
),
),
],
),
),
);
}
}
class PlusMinusEntry extends PopupMenuEntry<int> {
#override
double height = 100;
// height doesn't matter, as long as we are not giving
// initialValue to showMenu().
#override
bool represents(int n) => n == 1 || n == -1;
#override
PlusMinusEntryState createState() => PlusMinusEntryState();
}
class PlusMinusEntryState extends State<PlusMinusEntry> {
void _plus1() {
// This is how you close the popup menu and return user selection.
Navigator.pop<int>(context, 1);
}
void _minus1() {
Navigator.pop<int>(context, -1);
}
#override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Expanded(child: FlatButton(onPressed: _plus1, child: Text('+1'))),
Expanded(child: FlatButton(onPressed: _minus1, child: Text('-1'))),
],
);
}
}
If you are going to use a gridView or listview for laying out the images on the screen, you can wrap each item with a gesture detector then you should keep your images in a list somewhere, then simply remove the image from the list and call setState().
Something like the following. (This code will probably won't compile but it should give you the idea)
ListView.builder(
itemCount: imageList.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onLongPress: () {
showMenu(
onSelected: () => setState(() => imageList.remove(index))}
items: <PopupMenuEntry>[
PopupMenuItem(
value: this._index,
child: Row(
children: <Widget>[
Icon(Icons.delete),
Text("Delete"),
],
),
)
],
context: context,
);
},
child: imageList[index],
);
}
)
Edit: You can use a popup menu too, like following
Container(
margin: EdgeInsets.symmetric(vertical: 10),
height: 100,
width: 100,
child: PopupMenuButton(
child: FlutterLogo(),
itemBuilder: (context) {
return <PopupMenuItem>[new PopupMenuItem(child: Text('Delete'))];
},
),
),
Building on the answers by Nick Lee and hacker1024, but instead of turning the solution into a mixin, you could simply just turn it into a widget:
class PopupMenuContainer<T> extends StatefulWidget {
final Widget child;
final List<PopupMenuEntry<T>> items;
final void Function(T) onItemSelected;
PopupMenuContainer({#required this.child, #required this.items, #required this.onItemSelected, Key key}) : super(key: key);
#override
State<StatefulWidget> createState() => PopupMenuContainerState<T>();
}
class PopupMenuContainerState<T> extends State<PopupMenuContainer<T>>{
Offset _tapDownPosition;
#override
Widget build(BuildContext context) {
return GestureDetector(
onTapDown: (TapDownDetails details){
_tapDownPosition = details.globalPosition;
},
onLongPress: () async {
final RenderBox overlay = Overlay.of(context).context.findRenderObject();
T value = await showMenu<T>(
context: context,
items: widget.items,
position: RelativeRect.fromLTRB(
_tapDownPosition.dx,
_tapDownPosition.dy,
overlay.size.width - _tapDownPosition.dx,
overlay.size.height - _tapDownPosition.dy,
),
);
widget.onItemSelected(value);
},
child: widget.child
);
}
}
And then you'd use it like this:
child: PopupMenuContainer<String>(
child: Image.asset('assets/image.png'),
items: [
PopupMenuItem(value: 'delete', child: Text('Delete'))
],
onItemSelected: (value) async {
if( value == 'delete' ){
await showDialog(context: context, child: AlertDialog(
title: Text('Delete image'),
content: Text('Are you sure you want to delete the image?'),
actions: [
uiFlatButton(child: Text('NO'), onTap: (){ Navigator.of(context).pop(false); }),
uiFlatButton(child: Text('YES'), onTap: (){ Navigator.of(context).pop(true); }),
],
));
}
},
),
Adjust the code to fit your needs.
Nick Lee's answer can be turned into a mixin quite easily, which can then be used anywhere you want to use a popup menu.
The mixin:
import 'package:flutter/material.dart' hide showMenu;
import 'package:flutter/material.dart' as material show showMenu;
/// A mixin to provide convenience methods to record a tap position and show a popup menu.
mixin CustomPopupMenu<T extends StatefulWidget> on State<T> {
Offset _tapPosition;
/// Pass this method to an onTapDown parameter to record the tap position.
void storePosition(TapDownDetails details) => _tapPosition = details.globalPosition;
/// Use this method to show the menu.
Future<T> showMenu<T>({
#required BuildContext context,
#required List<PopupMenuEntry<T>> items,
T initialValue,
double elevation,
String semanticLabel,
ShapeBorder shape,
Color color,
bool captureInheritedThemes = true,
bool useRootNavigator = false,
}) {
final RenderBox overlay = Overlay.of(context).context.findRenderObject();
return material.showMenu<T>(
context: context,
position: RelativeRect.fromLTRB(
_tapPosition.dx,
_tapPosition.dy,
overlay.size.width - _tapPosition.dx,
overlay.size.height - _tapPosition.dy,
),
items: items,
initialValue: initialValue,
elevation: elevation,
semanticLabel: semanticLabel,
shape: shape,
color: color,
captureInheritedThemes: captureInheritedThemes,
useRootNavigator: useRootNavigator,
);
}
}
And then, to use it:
import 'package:flutter/material.dart';
import './custom_context_menu.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Popup Menu Usage',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Popup Menu Usage'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with CustomPopupMenu {
var _count = 0;
void _showCustomMenu() {
this.showMenu(
context: context,
items: <PopupMenuEntry<int>>[PlusMinusEntry()],
)
// This is how you handle user selection
.then<void>((int delta) {
// delta would be null if user taps on outside the popup menu
// (causing it to close without making selection)
if (delta == null) return;
setState(() {
_count = _count + delta;
});
});
// Another option:
//
// final delta = await showMenu(...);
//
// Then process `delta` however you want.
// Remember to make the surrounding function `async`, that is:
//
// void _showCustomMenu() async { ... }
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GestureDetector(
// This does not give the tap position ...
onLongPress: _showCustomMenu,
// Have to remember it on tap-down.
onTapDown: storePosition,
child: Container(
color: Colors.amberAccent,
padding: const EdgeInsets.all(100.0),
child: Text(
'$_count',
style: const TextStyle(fontSize: 100, fontWeight: FontWeight.bold),
),
),
),
],
),
),
);
}
}
class PlusMinusEntry extends PopupMenuEntry<int> {
#override
double height = 100;
// height doesn't matter, as long as we are not giving
// initialValue to showMenu().
#override
bool represents(int n) => n == 1 || n == -1;
#override
PlusMinusEntryState createState() => PlusMinusEntryState();
}
class PlusMinusEntryState extends State<PlusMinusEntry> {
void _plus1() {
// This is how you close the popup menu and return user selection.
Navigator.pop<int>(context, 1);
}
void _minus1() {
Navigator.pop<int>(context, -1);
}
#override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Expanded(child: FlatButton(onPressed: _plus1, child: Text('+1'))),
Expanded(child: FlatButton(onPressed: _minus1, child: Text('-1'))),
],
);
}
}
Answer for 2023
In Flutter 3.7 there is now a ContextMenuRegion widget that you can wrap around any existing widget. When the user long presses or right-clicks (depending on the platform), the menu you give it will appear.
return Scaffold(
body: Center(
child: ContextMenuRegion(
contextMenuBuilder: (context, offset) {
return AdaptiveTextSelectionToolbar.buttonItems(
anchors: TextSelectionToolbarAnchors(
primaryAnchor: offset,
),
buttonItems: <ContextMenuButtonItem>[
ContextMenuButtonItem(
onPressed: () {
ContextMenuController.removeAny();
},
label: 'Save',
),
],
);
},
child: const SizedBox(
width: 200.0,
height: 200.0,
child: FlutterLogo(),
),
),
),
);

How to update a widget state from another widget's build in flutter

My application has a Stack holding a CustomScrollView and a Container. The CustomScrollView has a SliverAppBar with an expanding header (FlexibleSpaceBar). The Container has properties which depend on the degree of expansion of the FlexibleSpaceBar.
I'm having difficulty getting the Container properties to update, in response to the SliverAppBar being manually expanded/collapsed, by the user.
My naive approach is to determine the expansion fraction during the build of the SliverAppBar's FlexibleSpaceBar (following the code in FlexibleSpaceBar.build) and then notify the Stack's parent, using setState.
However this causes the exception "setState() or markNeedsBuild() called during build."
What would be the correct way to use the artefact of FlexibleSpaceBar's build, to build the un-related widget?
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MyDemoApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'demo app',
home: MyHome(),
);
}
}
/// Notifies when there has been a change in the expansion or
/// collapsion[!] of the FlexibleSpace in the SliverAppBar
class FlexibleSpaceBarChangeNotification extends Notification {
final double collapsedFraction;
FlexibleSpaceBarChangeNotification({
this.collapsedFraction,
});
}
class MyHome extends StatefulWidget {
#override
_MyHomeState createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
double _headerCollapsedFraction = 0.5;
#override
Widget build(BuildContext context) {
return NotificationListener<FlexibleSpaceBarChangeNotification>(
onNotification: (FlexibleSpaceBarChangeNotification notification) {
// This notification occurs when the SliverAppBar is expanded/contracted
setState(() {
_headerCollapsedFraction = notification.collapsedFraction;
});
return true;
},
child: Stack(
children: <Widget>[
Material(
child: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
pinned: true,
expandedHeight: 200.0,
flexibleSpace: FlexibleSpaceBar(
title: MyFlexibleSpaceBarTitle(
// The MyFlexibleSpaceBarTitle widget
child: Text('A List of Items'),
),
),
),
SliverList(
delegate: SliverChildBuilderDelegate((context, i) =>
ListTile(
title: Text('List tile #$i'),
),
childCount: 50,
),
),
],
),
),
Container(
width: 100.0,
height: _headerCollapsedFraction * 100.0,
color: Colors.pink,
),
],
),
);
}
}
class MyFlexibleSpaceBarTitle extends StatefulWidget {
final Widget child;
MyFlexibleSpaceBarTitle({
this.child,
});
#override
_MyFlexibleSpaceBarTitleState createState() => _MyFlexibleSpaceBarTitleState();
}
class _MyFlexibleSpaceBarTitleState extends State<MyFlexibleSpaceBarTitle> {
#override
Widget build(BuildContext context) {
// Arithmetic mostly derived from FlexibleSpaceBar.build()
final FlexibleSpaceBarSettings settings = context.inheritFromWidgetOfExactType(FlexibleSpaceBarSettings);
assert(settings != null, 'No FlexibleSpaceBarSettings found');
final double deltaExtent = settings.maxExtent - settings.minExtent;
// 0.0 -> Expanded
// 1.0 -> Collapsed to toolbar
final double t = (1.0 - (settings.currentExtent - settings.minExtent) / deltaExtent).clamp(0.0, 1.0);
final double fadeStart = max(0.0, 1.0 - kToolbarHeight / deltaExtent);
const double fadeEnd = 1.0;
assert(fadeStart <= fadeEnd);
final double opacity = Interval(fadeStart, fadeEnd).transform(t);
// This is probably wrong ?
FlexibleSpaceBarChangeNotification(collapsedFraction: t)..dispatch(context);
return Opacity(
opacity: opacity,
child: widget.child,
);
}
}
You can implement state management using the provider package. This should enable you to update data from anywhere in the app. You can check this guide for more details.

Resources