Reputation: 32094
I'm writing a flutter app using Flutter 1.2.1.
inside the initState()
of my StatefulWidget
I call a showOverlay()
function that I created with the following code:
void showOverlay(BuildContext context) async {
final OverlayState overlayState = Overlay.of(context);
final OverlayEntry overlayEntry = OverlayEntry(
builder: (BuildContext context)=>Positioned(
left: 0.0,
right: 0,
bottom: 90.0,
child: Container(
margin: const EdgeInsets.all(15.0),
padding: const EdgeInsets.all(3.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
border: Border.all(color: Colors.blueAccent)
),
child:
Text('Focus, lighting and contrast help',style: TextStyle(fontWeight: FontWeight.normal,
color: Colors.white,
fontSize: 18.0,
decoration: TextDecoration.none)),
)
),
);
overlayState.insert(overlayEntry);
await Future<dynamic>.delayed(Duration(seconds: 2));
overlayEntry.remove();
}
the problem is that after the 2 seconds delay the overlay is still drawn on the screen.
what am I missing?
thanks
Upvotes: 4
Views: 6923
Reputation: 4387
For anyone who still need a solution after trying above suggested ones. Took me hours to find the problem. If you code happens to insert overlay entry object several times there is no working way to remove it. For example, accidentally executing this code for inserting overlay several times:
overlayEntry = _overlayEntryBuilder();
Overlay.of(context).insert(overlayEntry));
Then trying to remove:
overlayEntry?.remove();
overlayEntry = null;
Removing works only if you called
Overlay.of(context).insert(overlayEntry));
once. It probably creates several instances if you call it several times and remove won't work, it will stay active on your app. You may easily face this situatation if you use onChanged or .listen triggers inappropriately.
Upvotes: 7
Reputation: 32094
when I debugged I noticed the following warning:
This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
I googled and found this issue: https://github.com/flutter/flutter/issues/21638
so to resolve this I changed
overlayState.insert(overlayEntry);
to this:
WidgetsBinding.instance.addPostFrameCallback((_) => overlayState.insert(overlayEntry));
Upvotes: 6