How to detect when a TextField is selected in Flutter? - keyboard

I have a Flutter TextField which gets covered by the soft keyboard when the field is selected. I need to scroll the field up and out of the way when the keyboard is displayed. This is a pretty common problem and a solution is presented in this StackOverflow post.
I think I have the ScrollController part figured out but how do I detect when the TextField has been selected? There doesn't appear to be any event method (e.g. onFocus(), onSelected(), onTap(), etc).
I tried wrapping the TextField in a GestureDetector but that didn't work either -- apparently the event was never captured.
new GestureDetector(
child: new TextField(
decoration: const InputDecoration(labelText: 'City'),
),
onTap: () => print('Text Selected'),
),
This is such a basic requirement that I know there must be an easy solution.

I suppose you are looking for FocusNode.
To listen to focus change, you can add a listner to the FocusNode and specify the focusNode to TextField.
Example:
class TextFieldFocus extends StatefulWidget {
#override
_TextFieldFocusState createState() => _TextFieldFocusState();
}
class _TextFieldFocusState extends State<TextFieldFocus> {
FocusNode _focus = FocusNode();
TextEditingController _controller = TextEditingController();
#override
void initState() {
super.initState();
_focus.addListener(_onFocusChange);
}
#override
void dispose() {
super.dispose();
_focus.removeListener(_onFocusChange);
_focus.dispose();
}
void _onFocusChange() {
debugPrint("Focus: ${_focus.hasFocus.toString()}");
}
#override
Widget build(BuildContext context) {
return new Container(
color: Colors.white,
child: new TextField(
focusNode: _focus,
),
);
}
}
This gist represents how to ensure a focused node to be visible on the ui.

To be notified about a focus event, you can avoid manually managing widget's state, by using the utility classes FocusScope, Focus.
From the docs (https://api.flutter.dev/flutter/widgets/FocusNode-class.html):
Please see the Focus and FocusScope widgets, which are utility widgets that manage their own FocusNodes and FocusScopeNodes, respectively. If they aren't appropriate, FocusNodes can be managed directly.
Here is a simple example:
FocusScope(
child: Focus(
onFocusChange: (focus) => print("focus: $focus"),
child: TextField(
decoration: const InputDecoration(labelText: 'City'),
)
)
)

The easiest and simplest solution is to add the onTap method on TextField.
TextField(
onTap: () {
print('Editing stated $widget');
},
)

There is another way if your textfield needs to be disabled for some purpose like mine. for that case, you can wrap your textField with InkWell like this,
InkWell(
onTap: () {
print('clicked');
},
child: TextField(
enabled: false,
),
);

Related

How to I update the layout of my home screen when something in the navigation drawer is pressed in Flutter?

I want to make a Navigation drawer application. But instead of a pushing a new screen when something is presses I want update my initial screen. I cannot use setState(){} in my drawer to update the state of my home screen.
Please help me with this.
You can pass a function from your HomeScreen to your Drawer.
In your Drawer:
Class CustomDrawer{
final function updateMainScreen;
CustomDrawer(this.updateMainScreen);
}
In your MainScreen:
child: CustomDrawer(updateScreenFunction), //this function is where your MainScreen state gets changed
This way you can change whatever you want in your HomeScreen from anywhere else.
UPDATE: More Complete example. Note that this is very rough and only so you get an idea of how this works.
HomeScreenState:
class _HomeScreenWidgetState extends State<HomeScreenWidget> {
var containerColor = Colors.red;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: (Text('Hello')),
),
body: Container(
child: Column(
children: <Widget>[
Container(
height: 500,
width: 300,
color: containerColor,
),
CustomDrawer(
changeHomeScreen: changeContainerColor,
)
],
),
));
}
void changeContainerColor(Color col) {
setState(() {
containerColor = col;
});
}
}
The Mock Drawer widget:
class CustomDrawer extends StatelessWidget {
final Function changeHomeScreen;
CustomDrawer({this.changeHomeScreen});
#override
Widget build(BuildContext context) {
return Container(
child: FlatButton(
child: Text("Action in Drawer"),
onPressed: () => changeHomeScreen(Colors.blue),
),
);
}
}
You could also use a Provider for state management. Use the drawer to update the state (model) and use notifylisteners() to update your view. With conditionals pulled from the model, it is realy simple to create a 'single page' app.

Flutter Web : Need menu with sub menu

How to build Menu with Submenu like shown below in image using Flutter web
As of now flutter doesn't have a NestedMenu widget. However existing widgets can help build a custom menu which can have different submenu. Here in this dartPad I have created subMenu's using two different idea.
Using the Existing PopupMenuButon Widget nested one inside another and using the offset attribute to position the subMenu.
Using the global showMenufunction which can position the menu anywhere in the screen.
You can check the two implementations shown below. Note both methods has its own caveats. Like dismissing the popups and handling selection and cancelling. However this is only to show its possible in flutter and handling those cases is out of scope for this answer.
Nested PopupMenuButton
enum WhyFarther { harder, smarter, selfStarter, tradingCharter }
class MainMenu extends StatefulWidget {
MainMenu({Key key, this.title}) : super(key: key);
final String title;
#override
_MainMenuState createState() => _MainMenuState();
}
class _MainMenuState extends State<MainMenu> {
WhyFarther _selection = WhyFarther.smarter;
#override
Widget build(BuildContext context) {
// This menu button widget updates a _selection field (of type WhyFarther,
// not shown here).
return Padding(
padding: const EdgeInsets.all(2.0),
child: PopupMenuButton<WhyFarther>(
child: Material(
textStyle: Theme.of(context).textTheme.subtitle1,
elevation: 2.0,
child: Container(
padding: EdgeInsets.all(8),
child: Text(widget.title),
),
),
onSelected: (WhyFarther result) {
setState(() {
_selection = result;
});
},
itemBuilder: (BuildContext context) => <PopupMenuEntry<WhyFarther>>[
const PopupMenuItem<WhyFarther>(
value: WhyFarther.harder,
child: Text('Working a lot harder'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.smarter,
child: Text('Being a lot smarter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.selfStarter,
child: SubMenu('Sub Menu is too long'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: Text('Placed in charge of trading charter'),
),
],
),
);
}
}
class SubMenu extends StatefulWidget {
final String title;
const SubMenu(this.title);
#override
_SubMenuState createState() => _SubMenuState();
}
class _SubMenuState extends State<SubMenu> {
WhyFarther _selection = WhyFarther.smarter;
#override
Widget build(BuildContext context) {
// print(rendBox.size.bottomRight);
return PopupMenuButton<WhyFarther>(
child: Row(
children: <Widget>[
Text(widget.title),
Spacer(),
Icon(Icons.arrow_right, size: 30.0),
],
),
onCanceled: () {
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
},
onSelected: (WhyFarther result) {
setState(() {
_selection = result;
});
},
// how much the submenu should offset from parent. This seems to have an upper limit.
offset: Offset(300, 0),
itemBuilder: (BuildContext context) => <PopupMenuEntry<WhyFarther>>[
const PopupMenuItem<WhyFarther>(
value: WhyFarther.harder,
child: Text('Working a lot harder'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.smarter,
child: Text('Being a lot smarter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.selfStarter,
child: Text('Being a lot smarter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: Text('Placed in charge of trading charter'),
),
],
);
}
}
Using showMenu approach
class CustomMenu extends StatefulWidget {
const CustomMenu({Key key, this.title, this.rootMenu=false}) : super(key: key);
final String title;
final bool rootMenu;
#override
_CustomMenuState createState() => _CustomMenuState();
}
class _CustomMenuState extends State<CustomMenu> {
WhyFarther _selection = WhyFarther.smarter;
#override
Widget build(BuildContext context) {
// This menu button widget updates a _selection field (of type WhyFarther,
// not shown here).
return Padding(
padding: const EdgeInsets.all(2.0),
child: GestureDetector(
onTap: () {
// This offset should depend on the largest text and this is tricky when
// the menu items are changed
Offset offset = widget.rootMenu?Offset.zero:Offset(-300,0);
final RenderBox button = context.findRenderObject();
final RenderBox overlay =
Overlay.of(context).context.findRenderObject();
final RelativeRect position = RelativeRect.fromRect(
Rect.fromPoints(
button.localToGlobal(Offset.zero, ancestor: overlay),
button.localToGlobal(button.size.bottomRight(Offset.zero),
ancestor: overlay),
),
offset & overlay.size,
);
showMenu(
context: context,
position: position,
items: <PopupMenuEntry<WhyFarther>>[
const PopupMenuItem<WhyFarther>(
value: WhyFarther.harder,
child: Text('Working a lot harder'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.smarter,
child: Text('Being a lot smarter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.selfStarter,
child: CustomMenu(title: 'Sub Menu long'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: Text('Placed in charge of trading charter'),
),
]).then((selectedValue){
// do something with the value
if(Navigator.canPop(context)) Navigator.pop(context);
});
},
child: Material(
textStyle: Theme.of(context).textTheme.subtitle1,
elevation: widget.rootMenu?2.0:0.0,
child: Padding(
padding: widget.rootMenu? EdgeInsets.all(8.0):EdgeInsets.all(0.0),
child: Row(
children: <Widget>[
Text(widget.title),
if(!widget.rootMenu)
Spacer(),
if(!widget.rootMenu)
Icon(Icons.arrow_right),
],
),
),)
),
);
}
}
In standard Flutter library (material.dart), there is an abstract class PopupMenuEntry from which all children of PopupMenuButton are inherited. Currently, there are three concrete subclasses: PopupMenuItem (regular item you see all the time), 'CheckedPopupMenuItem' (regular item + checkbox) and PopupMenuDivider (horizontal line). There is nothing preventing us from implementing our own subclass.
Using the first answer of #AbhilashChandran and modifying it a bit, we can create the following generic class:
import 'package:flutter/material.dart';
/// An item with sub menu for using in popup menus
///
/// [title] is the text which will be displayed in the pop up
/// [items] is the list of items to populate the sub menu
/// [onSelected] is the callback to be fired if specific item is pressed
///
/// Selecting items from the submenu will automatically close the parent menu
/// Closing the sub menu by clicking outside of it, will automatically close the parent menu
class PopupSubMenuItem<T> extends PopupMenuEntry<T> {
const PopupSubMenuItem({
#required this.title,
#required this.items,
this.onSelected,
});
final String title;
final List<T> items;
final Function(T) onSelected;
#override
double get height => kMinInteractiveDimension; //Does not actually affect anything
#override
bool represents(T value) => false; //Our submenu does not represent any specific value for the parent menu
#override
State createState() => _PopupSubMenuState<T>();
}
/// The [State] for [PopupSubMenuItem] subclasses.
class _PopupSubMenuState<T> extends State<PopupSubMenuItem<T>> {
#override
Widget build(BuildContext context) {
return PopupMenuButton<T>(
tooltip: widget.title,
child: Padding(
padding: const EdgeInsets.only(left: 16.0, right: 8.0, top: 12.0, bottom: 12.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Expanded(
child: Text(widget.title),
),
Icon(
Icons.arrow_right,
size: 24.0,
color: Theme.of(context).iconTheme.color,
),
],
),
),
onCanceled: () {
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
},
onSelected: (T value) {
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
widget.onSelected?.call(value);
},
offset: Offset.zero, //TODO This is the most complex part - to calculate the correct position of the submenu being populated. For my purposes is does not matter where exactly to display it (Offset.zero will open submenu at the poistion where you tapped the item in the parent menu). Others might think of some value more appropriate to their needs.
itemBuilder: (BuildContext context) {
return widget.items
.map(
(item) => PopupMenuItem<T>(
value: item,
child: Text(item.toString()), //MEthod toString() of class T should be overridden to repesent something meaningful
),
)
.toList();
},
);
}
}
Usage of this class is simple and intuitive:
PopupMenuButton<int>(
icon: Icon(Icons.arrow_downward),
tooltip: 'Parent menu',
onSelected: (value) {
//Do something with selected parent value
},
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
PopupMenuItem<int>(
value: 10,
child: Text('Item 10'),
),
PopupMenuItem<int>(
value: 20,
child: Text('Item 20'),
),
PopupMenuItem<int>(
value: 50,
child: Text('Item 50'),
),
PopupSubMenuItem<int>(
title: 'Other items',
items: [
100,
200,
300,
400,
500,
],
onSelected: (value) {
//Do something with selected child value
},
),
];
},
)
The result is something like this:
There are a couple of drawbacks for this approach:
Obviously, the submenu is displayed not at the location you wanted it to be displayed - may be dealt with by some complex calculations;
Even though several submenus can be placed one inside another, I am not sure that the top ones will be closed correctly when bottom ones are closed (or the value is selected) - may be dealt with by Navigator calls and checks;
Both parent menu and submenues should have values of the same type - mayn be dealt with by using subclasses;
The need to specify onSelected method twice (for parent menu and for child menu) - may be dealt with by using methods or closures;
Some other things I may have not thought of - may be dealt with by writing comments below.
The PopupSubMenuItem class can be expanded to include something like final String Function(T) formatter; to represent your values in a meaningful way, but for the sake of brevity this functionality was omitted.

How to add Pie chart in hole of Donut chart in Flutter, I tried with Stack widget but it's working for text only

I am trying to fill the hole of donut chart with pie chart in Flutter for my project but unable to do so.
Expanded(
child:Stack(
children:<Widget>[
charts.PieChart(
_seriesPieData1,
animate: true,
animationDuration: Duration(milliseconds: 500),
selectionModels: [
new charts.SelectionModelConfig(
type: charts.SelectionModelType.info,
),
],
defaultRenderer: new charts.ArcRendererConfig(arcWidth: 25),
),
Center
(
child: charts.PieChart(
_seriesPieData,
animate: true,
animationDuration: Duration(milliseconds: 500),
selectionModels: [
new charts.SelectionModelConfig(
type: charts.SelectionModelType.info,
),
],
defaultRenderer: new charts.ArcRendererConfig(arcRendererDecorators: [
new charts.ArcLabelDecorator(
labelPosition: charts.ArcLabelPosition.inside)
],),
),
),
],
),
),
I use Container and set same height and width of these two chart.
child: Stack(
children: <Widget>[
Container(
//color: Colors.blue,
height: 300.0,
width: 300.0,
child: dpc,
),
Container(
// color: Colors.blue,
height: 300.0,
width: 300.0,
child: PieChart(dataMap: dataMap, showLegends: false,),
)
full code
import 'package:flutter/material.dart';
/// Donut chart example. This is a simple pie chart with a hole in the middle.
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:pie_chart/pie_chart.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();
}
Map<String, double> dataMap = new Map();
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
#override
void initState() {
super.initState();
dataMap.putIfAbsent("Flutter", () => 5);
dataMap.putIfAbsent("React", () => 3);
dataMap.putIfAbsent("Xamarin", () => 2);
dataMap.putIfAbsent("Ionic", () => 2);
}
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) {
var dpc = DonutPieChart.withSampleData();
// 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: Stack(
// Column is also 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>[
Container(
//color: Colors.blue,
height: 300.0,
width: 300.0,
child: dpc,
),
Container(
// color: Colors.blue,
height: 300.0,
width: 300.0,
child: PieChart(dataMap: dataMap, showLegends: false,),
)
,
/* Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),*/
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class DonutPieChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
DonutPieChart(this.seriesList, {this.animate});
/// Creates a [PieChart] with sample data and no transition.
factory DonutPieChart.withSampleData() {
return new DonutPieChart(
_createSampleData(),
// Disable animations for image tests.
animate: false,
);
}
#override
Widget build(BuildContext context) {
return new charts.PieChart(seriesList,
animate: animate,
// Configure the width of the pie slices to 60px. The remaining space in
// the chart will be left as a hole in the center.
defaultRenderer: new charts.ArcRendererConfig(arcWidth: 60));
}
/// Create one series with sample hard coded data.
static List<charts.Series<LinearSales, int>> _createSampleData() {
final data = [
new LinearSales(0, 100),
new LinearSales(1, 75),
new LinearSales(2, 25),
new LinearSales(3, 5),
];
return [
new charts.Series<LinearSales, int>(
id: 'Sales',
domainFn: (LinearSales sales, _) => sales.year,
measureFn: (LinearSales sales, _) => sales.sales,
data: data,
)
];
}
}
/// Sample linear data type.
class LinearSales {
final int year;
final int sales;
LinearSales(this.year, this.sales);
}

Place text box in appbar in Flutter

I want to implement an Appbar like below where there are a textbox and multiple icons:
The icons can be added in action easily, but how to add the text box and add search action to it. There are many search bar plugins available, but all of them occupy the whole app bar and no way to mention the hints. Can anyone give some idea, it will be a great help for me.
In the title propiery, inside the AppBar, you can pass a widget, which means you can add any component you want, like a TextField. see the example below:
appBar: AppBar(
title: TextField(
decoration: InputDecoration(
hintText: 'Search',
prefixIcon: Icon(Icons.search)
),
),
),
I suggest to you, to wrap this TextField in a GestureDetector, disable the TextField with the proprierty called enable (set to false), and in the onTap method inside the GestureDetector, you can call a showSearch() method.
To call this showSearch(), you'll need to pass a context and a searchDelegate which is a component that extends a class, check this example:
class CustomSearchDelegate extends SearchDelegate {
#override
List<Widget> buildActions(BuildContext context) {
// TODO: implement buildActions
return null;
}
#override
Widget buildLeading(BuildContext context) {
// TODO: implement buildLeading
return null;
}
#override
Widget buildResults(BuildContext context) {
// TODO: implement buildResults
return null;
}
#override
Widget buildSuggestions(BuildContext context) {
// TODO: implement buildSuggestions
return null;
}
}
Source: Implementing search in Flutter
Now, you can do this:
GestureDetector:
onTap: () => showSearch(context: context, delegate: CustomSearchScreen()),
child: ....

Flutter | How to show AlertDialog on top of any overlay?

How to show AlertDialog always on top of anything on the screen?
Code:
import 'package:flutter/material.dart';
class CountriesField extends StatefulWidget {
#override
_CountriesFieldState createState() => _CountriesFieldState();
}
class _CountriesFieldState extends State<CountriesField> {
final FocusNode _focusNode = FocusNode();
OverlayEntry _overlayEntry;
final LayerLink _layerLink = LayerLink();
#override
void initState() {
_focusNode.addListener(() {
if (_focusNode.hasFocus) {
this._overlayEntry = this._createOverlayEntry();
Overlay.of(context).insert(this._overlayEntry);
} else {
// this._overlayEntry.remove();
}
});
}
OverlayEntry _createOverlayEntry() {
RenderBox renderBox = context.findRenderObject();
var size = renderBox.size;
return OverlayEntry(
builder: (context) => Positioned(
width: size.width,
child: CompositedTransformFollower(
link: this._layerLink,
showWhenUnlinked: false,
offset: Offset(0.0, size.height + 5.0),
child: Material(
elevation: 4.0,
child: ListView(
padding: EdgeInsets.zero,
shrinkWrap: true,
children: <Widget>[
ListTile(
title: Text('Syria'),
onTap: () {
print('Syria Tapped');
},
),
ListTile(
title: Text('Lebanon'),
onTap: () {
print('Lebanon Tapped');
},
)
],
),
),
),
));
}
#override
Widget build(BuildContext context) {
return CompositedTransformTarget(
link: this._layerLink,
child: Material(
child: TextFormField(
focusNode: this._focusNode,
decoration: InputDecoration(labelText: 'Country'),
),
),
);
}
}
class FormPage extends StatefulWidget {
#override
_FormPageState createState() => _FormPageState();
}
class _FormPageState extends State<FormPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Material(elevation: 4.0, child: CountriesField()),
RaisedButton(
child: Text('Help dialog'),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Help"),
content: Text("This should show on top of any overlay"),
actions: <Widget>[
FlatButton(
child: Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
},
)
],
),
);
}
}
There is no easy way to make dialogs appear on top of overlays. Depends on your use case, you can either convert both to Overlay, or convert both to Dialog.
This is an example of converting both to dialogs, using showDialog method:
You don't have to return an AlertDialog widget when showing a dialog, for example, here I'm returning a Container with white filling, and contains a ListView for the "Menu A" dialog in the back.
When using showDialog, you get automatic features such as dimming the background and click anywhere outside to dismiss. If you don't want these or any other dialog things, and if you cannot find a way to disable them easily, you can always go the other way around and convert both to Overlay instead.
For overlays, whichever gets inserted latest, is displayed on top.
This isn't really a "fix", but a potential workaround for this is to basically not use Overlays and rely on a top level Stack.
If you are using Positioned in your Overlay anyway, putting your widget in a top level Stack doesn't interfere with things like Dialogs (and you potentially have more control over which areas of your app show the overlay).
Example:
class StackOverlayState extends State<StackOverlay> {
bool _showOverlay = true; // This could also easily be a list of widgets
Widget build(BuildContext context) {
return Stack(
children: [
Positioned.fill(
child: Scaffold(
body: /// etc..
),
),
if (_showOverlay)
MyOverlayWidget(),
],
);
}
}
I was using Overlays, and switching to just using a Stack instead seems to have caused no issues and required no code changes in the Overlay widget itself, but YMMV.

Resources