Skip to content

Instantly share code, notes, and snippets.

@zaun
Created July 21, 2019 05:14
Show Gist options
  • Save zaun/6313e5143e8183baa0c2ac5e155d8d2c to your computer and use it in GitHub Desktop.
Save zaun/6313e5143e8183baa0c2ac5e155d8d2c to your computer and use it in GitHub Desktop.
Uncomments the code at 61, 106 or 114 will cause the error `MediaQuery.of() called with a context that does not contain a MediaQuery.`
import 'dart:async';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'views/main_view.dart';
import 'views/update_view.dart';
import 'store.dart';
import 'recordKeeper/store.dart';
final RecordKeeper<AppState> appStore = RecordKeeper<AppState>(
AppState('http://192.168.5.52:8080'),
AppActions()
);
void main() => runApp(App(appStore));
class LifecycleEventHandler extends WidgetsBindingObserver {
LifecycleEventHandler({this.onResume, this.onSuspend});
final VoidCallback onResume;
final VoidCallback onSuspend;
@override
Future<Null> didChangeAppLifecycleState(AppLifecycleState state) async {
switch (state) {
case AppLifecycleState.inactive:
case AppLifecycleState.paused:
case AppLifecycleState.suspending:
onSuspend();
break;
case AppLifecycleState.resumed:
onResume();
break;
}
}
}
class App extends StatefulWidget {
final RecordKeeper<AppState> appStore;
App(this.appStore);
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
bool _isUpdated;
initState() {
super.initState();
this._isUpdated = false;
WidgetsBinding.instance.addObserver(
LifecycleEventHandler(onResume: _onAppResume, onSuspend: _onAppSuspend)
);
// SchedulerBinding.instance.addPostFrameCallback((_) {
// _lockState();
// });
}
void _lockState() {
// Can't use RecordKeeperWidgetState yet so calculate
// itTablet here manually
MediaQueryData query = MediaQuery.of(context);
Size size = query.size;
double diagonal = sqrt(
(size.width * size.width) +
(size.height * size.height)
);
bool isTablet = diagonal > 1100.0;
if (!isTablet) {
print('Lock screen on phones');
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitDown,
DeviceOrientation.portraitUp,
]);
}
}
void _onAppResume() {
setState(() => this._isUpdated = false);
}
void _onAppSuspend() {
}
void _onFinishedUpdates() {
setState(() => this._isUpdated = true);
}
Widget _getCurrentView() {
if (_isUpdated) {
return MainView();
} else {
return UpdateView(onFinshedUpdates: _onFinishedUpdates);
}
}
// @override
// void didChangeDependencies() {
// super.didChangeDependencies();
// _lockState();
// }
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
// _lockState();
return RecordKeeperProvider(
store: widget.appStore,
child: CupertinoApp(
home: _getCurrentView()
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment