Skip to content

Instantly share code, notes, and snippets.

@iapicca
Last active September 9, 2024 09:52
Show Gist options
  • Save iapicca/805a701f2197f86459125efa2ee63ee8 to your computer and use it in GitHub Desktop.
Save iapicca/805a701f2197f86459125efa2ee63ee8 to your computer and use it in GitHub Desktop.
DeviceOrientation example
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(context) => const MaterialApp(
home: MyHomePage(),
);
}
class MyHomePage extends StatefulWidget {
const MyHomePage({
super.key,
});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late final ValueNotifier<DeviceOrientation> _valueNotifier;
@override
void initState() {
_valueNotifier = ValueNotifier(DeviceOrientation.portraitUp)
..addListener(_listener);
super.initState();
}
@override
void dispose() {
_valueNotifier
..removeListener(_listener)
..dispose();
super.dispose();
}
void _next() {
var next = DeviceOrientation.values.indexOf(_valueNotifier.value) + 1;
if (!(next < DeviceOrientation.values.length)) {
next = 0;
}
setState(() => _valueNotifier.value = DeviceOrientation.values[next]);
}
void _listener() => SystemChrome.setPreferredOrientations(
[_valueNotifier.value],
);
@override
Widget build(context) => Scaffold(
body: Center(
child: ValueListenableBuilder(
valueListenable: _valueNotifier,
builder: (context, orientation, _) => Text(orientation.name),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _next,
tooltip: 'next',
child: const Icon(Icons.rotate_90_degrees_cw),
),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment