Problem:
I am learning Flutter, and the app bar on top in the Basic Widgets section of the Introduction to widgets section of the Flutter docs is being blocked by the notch of an iPhone or phone simulator, as seen below. How can I fix this?
Notes:
This bug was confirmed in April 2020. It's possible that the Flutter team has updated their documentation by the time you are reading this. (If so, thank you Flutter team!)
Also note that this how-to is just one way to workaround the issue. The later code in the Flutter documentation shows better practices on which widgets to use, etc., to avoid the notch. That being said, this workaround is for anyone who is trying to debug this before moving on.
Workaround:
The workaround is highlighted below, followed by a brief explanation:
import 'package:flutter/material.dart';
class MyAppBar extends StatelessWidget {
MyAppBar({this.title});
// Fields in a Widget subclass are always marked "final".
final Widget title;
@override
Widget build(BuildContext context) {
return Container(
height: 56.0, // in logical pixels
padding: const EdgeInsets.symmetric(horizontal: 8.0),
decoration: BoxDecoration(color: Colors.blue[500]),
// Row is a horizontal, linear layout.
child: Row(
// is the type of items in the list.
children: [
IconButton(
icon: Icon(Icons.menu),
tooltip: 'Navigation menu',
onPressed: null, // null disables the button
),
// Expanded expands its child to fill the available space.
Expanded(
child: title,
),
IconButton(
icon: Icon(Icons.search),
tooltip: 'Search',
onPressed: null,
),
],
),
);
}
}
class MyScaffold extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Material is a conceptual piece of paper on which the UI appears.
return Material(
child: SafeArea(
// Column is a vertical, linear layout.
child: Column(
children: [
MyAppBar(
title: Text(
'Example title',
style: Theme.of(context).primaryTextTheme.title,
),
),
Expanded(
child: Center(
child: Text('Hello, world!'),
),
),
],
),
), // SafeArea
); // Material
}
}
void main() {
runApp(MaterialApp(
title: 'My app', // used by the OS task switcher
home: MyScaffold(),
));
}
The above code encloses the other widgets in the example code within the safe area of the device via the SafeArea widget - a class that adds appropriate insets for a given device.
If all went well, your results should now look similar to the image below and you can now move on to learning more Flutter, free from the iPhone-notch-overlap.
If you'd like to learn more, please check out the references below.
References:
- https://api.flutter.dev/flutter/widgets/SafeArea-class.html
- https://github.com/flutter/flutter/issues/4518 (similar question/issue with more discussion)
No comments:
Post a Comment