Skip to content

Instantly share code, notes, and snippets.

@iapicca
Created September 9, 2024 18:01
Show Gist options
  • Save iapicca/9b77b71ca6dbc77c7c88828f99a96421 to your computer and use it in GitHub Desktop.
Save iapicca/9b77b71ca6dbc77c7c88828f99a96421 to your computer and use it in GitHub Desktop.
DeviceOrientation web
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);
super.initState();
}
@override
void dispose() {
_valueNotifier.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]);
}
@override
Widget build(context) => ValueListenableBuilder(
valueListenable: _valueNotifier,
builder: (context, orientation, _) => FakeDeviceOrientationWidget(
orientation: orientation,
child: Scaffold(
body: Center(
child: Text(orientation.name),
),
floatingActionButton: FloatingActionButton(
onPressed: _next,
tooltip: 'next',
child: const Icon(Icons.rotate_90_degrees_cw),
),
),
),
);
}
class FakeDeviceOrientationWidget extends StatelessWidget {
final DeviceOrientation orientation;
final Widget child;
const FakeDeviceOrientationWidget({
super.key,
required this.orientation,
required this.child,
});
@override
Widget build(context) => RotatedBox(
quarterTurns: switch (orientation) {
DeviceOrientation.portraitUp => 0,
DeviceOrientation.portraitDown => 2,
DeviceOrientation.landscapeLeft => 1,
DeviceOrientation.landscapeRight => 3
},
child: child,
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment