I'm writing code for a PaginatedDataTable, but I get lost when I try to use showDialog(). What I want is when the user presses a row in the DataTable, a dialog box appears with information that row contains. The problem I'm having, is the context for the Dialog box, because it requires context, and the DataRow class doesn't innately have context.
In order to recognize that a row has been selected, you have to use onSelectChanged() in the DataRow class. Here, I'm trying to call the dialog box, but I have to use a Global navigator key.
class CalendarResultsDataSource extends DataTableSource {
final List<CalendarResult> _calendarResults;
CalendarResultsDataSource(this._calendarResults);
@override
DataRow getRow(int index) {
assert(index >= 0);
if (index >= _calendarResults.length) return null;
final CalendarResult calendarResult = _calendarResults[index];
return DataRow.byIndex(
index: index,
selected: calendarResult.selected,
onSelectChanged: (bool value) {
print(value);
print(calendarResult.agency);
Dialogs.showAuditInfo(
navigatorKey.currentState.overlay.context, calendarResult); //<-- this feels hacky
},
cells: <DataCell>[
DataCell(Container(
height: double.infinity,
width: double.infinity,
color: index.isEven
? ColorDefs.colorAlternatingDark
: ColorDefs.colorDarkBackground,
child: Padding(
padding: const EdgeInsets.fromLTRB(6.0, 4.0, 4.0, 4.0),
child: Center(
child: Text('${calendarResult.getDateFormatted()}',
style: ColorDefs.textBodyWhite15)),
))), etc. etc.
]);
in the dataRow class.
So, I created a navigator key in main() like this:
final navigatorKey = GlobalKey<NavigatorState>();
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
home: Scaffold(body: AwesomeAppCodeHere())
);
}
}
Then, I'm referring to that key in the onSelectChanged() method like this:
showDialog<void>(
context: navigatorKey.currentState.overlay.context,
builder: (BuildContext context) {
return AlertDialog(
content: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return DialogInnards();
},
),
);
},
);
But, it feels hacky. The only other solution I can think of is to pass context to the DataRow class from the PaginatedDataTable widget, but then I'd have to modify the flutter DataRow widget directly.
So, what's the best way to get context in a class without an exposed context?
I did see the 'get' package: might work... https://pub.dev/packages/get but isn't that overkill for something that is straightforward? (but just escaping me?)