Flutter web font scaling - flutter-web

[example] 1As far as i can understand the issue, strings outgrow the Text widget when increasing zoom on browser. The issue comes in all browsers except Google Chrome. In case of Google Chrome page just ignores zoom. What would be the workaround if there is any?
class TextField extends AuthField {
TextField(
{super.key,
required super.apiKey,
required super.title,
required super.description,
required this.controller,
required super.isRequired})
: super(type: "textfield");
final TextEditingController controller;
#override
Map<String, dynamic> commit() {
data = controller.text;
return {"type": type, "title": title, "api_name": apiKey, "value": data};
}
#override
State<TextField> createState() => TextFieldState();
}
class TextFieldState extends State<TextField> {
#override
Widget build(BuildContext context) {
return TextFormField(
style: textStyleLittle,
validator: (widget.isRequired)
? (value) {
if (value == null || value.isEmpty) {
return "This field can not be empty";
}
return null;
}
: null,
textInputAction: TextInputAction.next,
onEditingComplete: () => FocusScope.of(context).nextFocus(),
controller: widget.controller,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelStyle: textStyleLittle,
hintStyle: textStyleLittle,
hintText: widget.description,
label: AutoSizeText(
widget.title,
style: textStyleLittle,
wrapWords: false,
),
),
);
}
}
I tried using auto_size_text package, i tried dynamically changing the font size by inverse proportion, but it seems font size does not scale linearly.

Related

What are these API_KEY and MAP_API_KEY in the example given in the official documentation of flutter_polyline_point

Here is the example given in the Flutter document of flutter_polyline_point
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'Constants.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Polyline example',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.orange,
),
home: MapScreen(),
);
}
}
class MapScreen extends StatefulWidget {
#override
_MapScreenState createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
GoogleMapController mapController;
double _originLatitude = 6.5212402, _originLongitude = 3.3679965;
double _destLatitude = 6.849660, _destLongitude = 3.648190;
Map<MarkerId, Marker> markers = {};
Map<PolylineId, Polyline> polylines = {};
List<LatLng> polylineCoordinates = [];
PolylinePoints polylinePoints = PolylinePoints();
String googleAPiKey = Constants.MAP_API_KEY;
#override
void initState() {
super.initState();
/// origin marker
_addMarker(LatLng(_originLatitude, _originLongitude), "origin",
BitmapDescriptor.defaultMarker);
/// destination marker
_addMarker(LatLng(_destLatitude, _destLongitude), "destination",
BitmapDescriptor.defaultMarkerWithHue(90));
_getPolyline();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(_originLatitude, _originLongitude), zoom: 15),
myLocationEnabled: true,
tiltGesturesEnabled: true,
compassEnabled: true,
scrollGesturesEnabled: true,
zoomGesturesEnabled: true,
onMapCreated: _onMapCreated,
markers: Set<Marker>.of(markers.values),
polylines: Set<Polyline>.of(polylines.values),
)),
);
}
void _onMapCreated(GoogleMapController controller) async {
mapController = controller;
}
_addMarker(LatLng position, String id, BitmapDescriptor descriptor) {
MarkerId markerId = MarkerId(id);
Marker marker =
Marker(markerId: markerId, icon: descriptor, position: position);
markers[markerId] = marker;
}
_addPolyLine() {
PolylineId id = PolylineId("poly");
Polyline polyline = Polyline(
polylineId: id, color: Colors.red, points: polylineCoordinates);
polylines[id] = polyline;
setState(() {});
}
_getPolyline() async {
PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
Constants.API_KEY,
PointLatLng(_originLatitude, _originLongitude),
PointLatLng(_destLatitude, _destLongitude),
travelMode: TravelMode.driving,
wayPoints: [PolylineWayPoint(location: "Sabo, Yaba Lagos Nigeria")]
);
if (result.points.isNotEmpty) {
result.points.forEach((PointLatLng point) {
polylineCoordinates.add(LatLng(point.latitude, point.longitude));
});
}
_addPolyLine();
}
}
What is the difference between API_KEY and MAP_API_KEY? I am getting error there while trying to execute the example.
My requirement is to get the polyline points between two places in google map.
Kindly suggest me some examples to get the polyline drawn; if you have. I am getting problem in drawing the routes. Tried many examples but not getting it.
To use google maps, you need to get an API key from the following link:
https://developers.google.com/maps/documentation/javascript/get-api-key
This should be the MAP_API_KEY constant.
To use the direction api, you need to get an API key from the following link:
https://developers.google.com/maps/documentation/directions/get-api-key
This should be the API_KEY constant.

Flutter Web : Need menu with sub menu

How to build Menu with Submenu like shown below in image using Flutter web
As of now flutter doesn't have a NestedMenu widget. However existing widgets can help build a custom menu which can have different submenu. Here in this dartPad I have created subMenu's using two different idea.
Using the Existing PopupMenuButon Widget nested one inside another and using the offset attribute to position the subMenu.
Using the global showMenufunction which can position the menu anywhere in the screen.
You can check the two implementations shown below. Note both methods has its own caveats. Like dismissing the popups and handling selection and cancelling. However this is only to show its possible in flutter and handling those cases is out of scope for this answer.
Nested PopupMenuButton
enum WhyFarther { harder, smarter, selfStarter, tradingCharter }
class MainMenu extends StatefulWidget {
MainMenu({Key key, this.title}) : super(key: key);
final String title;
#override
_MainMenuState createState() => _MainMenuState();
}
class _MainMenuState extends State<MainMenu> {
WhyFarther _selection = WhyFarther.smarter;
#override
Widget build(BuildContext context) {
// This menu button widget updates a _selection field (of type WhyFarther,
// not shown here).
return Padding(
padding: const EdgeInsets.all(2.0),
child: PopupMenuButton<WhyFarther>(
child: Material(
textStyle: Theme.of(context).textTheme.subtitle1,
elevation: 2.0,
child: Container(
padding: EdgeInsets.all(8),
child: Text(widget.title),
),
),
onSelected: (WhyFarther result) {
setState(() {
_selection = result;
});
},
itemBuilder: (BuildContext context) => <PopupMenuEntry<WhyFarther>>[
const PopupMenuItem<WhyFarther>(
value: WhyFarther.harder,
child: Text('Working a lot harder'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.smarter,
child: Text('Being a lot smarter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.selfStarter,
child: SubMenu('Sub Menu is too long'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: Text('Placed in charge of trading charter'),
),
],
),
);
}
}
class SubMenu extends StatefulWidget {
final String title;
const SubMenu(this.title);
#override
_SubMenuState createState() => _SubMenuState();
}
class _SubMenuState extends State<SubMenu> {
WhyFarther _selection = WhyFarther.smarter;
#override
Widget build(BuildContext context) {
// print(rendBox.size.bottomRight);
return PopupMenuButton<WhyFarther>(
child: Row(
children: <Widget>[
Text(widget.title),
Spacer(),
Icon(Icons.arrow_right, size: 30.0),
],
),
onCanceled: () {
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
},
onSelected: (WhyFarther result) {
setState(() {
_selection = result;
});
},
// how much the submenu should offset from parent. This seems to have an upper limit.
offset: Offset(300, 0),
itemBuilder: (BuildContext context) => <PopupMenuEntry<WhyFarther>>[
const PopupMenuItem<WhyFarther>(
value: WhyFarther.harder,
child: Text('Working a lot harder'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.smarter,
child: Text('Being a lot smarter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.selfStarter,
child: Text('Being a lot smarter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: Text('Placed in charge of trading charter'),
),
],
);
}
}
Using showMenu approach
class CustomMenu extends StatefulWidget {
const CustomMenu({Key key, this.title, this.rootMenu=false}) : super(key: key);
final String title;
final bool rootMenu;
#override
_CustomMenuState createState() => _CustomMenuState();
}
class _CustomMenuState extends State<CustomMenu> {
WhyFarther _selection = WhyFarther.smarter;
#override
Widget build(BuildContext context) {
// This menu button widget updates a _selection field (of type WhyFarther,
// not shown here).
return Padding(
padding: const EdgeInsets.all(2.0),
child: GestureDetector(
onTap: () {
// This offset should depend on the largest text and this is tricky when
// the menu items are changed
Offset offset = widget.rootMenu?Offset.zero:Offset(-300,0);
final RenderBox button = context.findRenderObject();
final RenderBox overlay =
Overlay.of(context).context.findRenderObject();
final RelativeRect position = RelativeRect.fromRect(
Rect.fromPoints(
button.localToGlobal(Offset.zero, ancestor: overlay),
button.localToGlobal(button.size.bottomRight(Offset.zero),
ancestor: overlay),
),
offset & overlay.size,
);
showMenu(
context: context,
position: position,
items: <PopupMenuEntry<WhyFarther>>[
const PopupMenuItem<WhyFarther>(
value: WhyFarther.harder,
child: Text('Working a lot harder'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.smarter,
child: Text('Being a lot smarter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.selfStarter,
child: CustomMenu(title: 'Sub Menu long'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: Text('Placed in charge of trading charter'),
),
]).then((selectedValue){
// do something with the value
if(Navigator.canPop(context)) Navigator.pop(context);
});
},
child: Material(
textStyle: Theme.of(context).textTheme.subtitle1,
elevation: widget.rootMenu?2.0:0.0,
child: Padding(
padding: widget.rootMenu? EdgeInsets.all(8.0):EdgeInsets.all(0.0),
child: Row(
children: <Widget>[
Text(widget.title),
if(!widget.rootMenu)
Spacer(),
if(!widget.rootMenu)
Icon(Icons.arrow_right),
],
),
),)
),
);
}
}
In standard Flutter library (material.dart), there is an abstract class PopupMenuEntry from which all children of PopupMenuButton are inherited. Currently, there are three concrete subclasses: PopupMenuItem (regular item you see all the time), 'CheckedPopupMenuItem' (regular item + checkbox) and PopupMenuDivider (horizontal line). There is nothing preventing us from implementing our own subclass.
Using the first answer of #AbhilashChandran and modifying it a bit, we can create the following generic class:
import 'package:flutter/material.dart';
/// An item with sub menu for using in popup menus
///
/// [title] is the text which will be displayed in the pop up
/// [items] is the list of items to populate the sub menu
/// [onSelected] is the callback to be fired if specific item is pressed
///
/// Selecting items from the submenu will automatically close the parent menu
/// Closing the sub menu by clicking outside of it, will automatically close the parent menu
class PopupSubMenuItem<T> extends PopupMenuEntry<T> {
const PopupSubMenuItem({
#required this.title,
#required this.items,
this.onSelected,
});
final String title;
final List<T> items;
final Function(T) onSelected;
#override
double get height => kMinInteractiveDimension; //Does not actually affect anything
#override
bool represents(T value) => false; //Our submenu does not represent any specific value for the parent menu
#override
State createState() => _PopupSubMenuState<T>();
}
/// The [State] for [PopupSubMenuItem] subclasses.
class _PopupSubMenuState<T> extends State<PopupSubMenuItem<T>> {
#override
Widget build(BuildContext context) {
return PopupMenuButton<T>(
tooltip: widget.title,
child: Padding(
padding: const EdgeInsets.only(left: 16.0, right: 8.0, top: 12.0, bottom: 12.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Expanded(
child: Text(widget.title),
),
Icon(
Icons.arrow_right,
size: 24.0,
color: Theme.of(context).iconTheme.color,
),
],
),
),
onCanceled: () {
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
},
onSelected: (T value) {
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
widget.onSelected?.call(value);
},
offset: Offset.zero, //TODO This is the most complex part - to calculate the correct position of the submenu being populated. For my purposes is does not matter where exactly to display it (Offset.zero will open submenu at the poistion where you tapped the item in the parent menu). Others might think of some value more appropriate to their needs.
itemBuilder: (BuildContext context) {
return widget.items
.map(
(item) => PopupMenuItem<T>(
value: item,
child: Text(item.toString()), //MEthod toString() of class T should be overridden to repesent something meaningful
),
)
.toList();
},
);
}
}
Usage of this class is simple and intuitive:
PopupMenuButton<int>(
icon: Icon(Icons.arrow_downward),
tooltip: 'Parent menu',
onSelected: (value) {
//Do something with selected parent value
},
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
PopupMenuItem<int>(
value: 10,
child: Text('Item 10'),
),
PopupMenuItem<int>(
value: 20,
child: Text('Item 20'),
),
PopupMenuItem<int>(
value: 50,
child: Text('Item 50'),
),
PopupSubMenuItem<int>(
title: 'Other items',
items: [
100,
200,
300,
400,
500,
],
onSelected: (value) {
//Do something with selected child value
},
),
];
},
)
The result is something like this:
There are a couple of drawbacks for this approach:
Obviously, the submenu is displayed not at the location you wanted it to be displayed - may be dealt with by some complex calculations;
Even though several submenus can be placed one inside another, I am not sure that the top ones will be closed correctly when bottom ones are closed (or the value is selected) - may be dealt with by Navigator calls and checks;
Both parent menu and submenues should have values of the same type - mayn be dealt with by using subclasses;
The need to specify onSelected method twice (for parent menu and for child menu) - may be dealt with by using methods or closures;
Some other things I may have not thought of - may be dealt with by writing comments below.
The PopupSubMenuItem class can be expanded to include something like final String Function(T) formatter; to represent your values in a meaningful way, but for the sake of brevity this functionality was omitted.

How to set dynamic initialRoute based on sharedPrefs value in flutter?

Currently, I am working around routes and i wanted to set initialRoute in my app based on sharedPreferences value.
I am using Statedulwidget for my MaterialAppWidget and using setState() method once the data from sharedPrefs is fetched. But, every time i am getting the same screen.
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int initScreen = 0;
initPrefs() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
initScreen = prefs.getInt("initScreen");
print("initScreen ${initScreen}");
setState(() {});
}
#override
void initState() {
super.initState();
initPrefs();
}
#override
Widget build(BuildContext context) {
print("initScreen2 ${initScreen}");
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Authentication',
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: initScreen == 0 || initScreen == null
? MediatorPage.routeName
: PopUntilPage.routeName,
routes: {
CloudGroupCreate.routeName: (context) => CloudGroupCreate(),
CloudDashboard.routeName: (context) => CloudDashboard(),
PopUntilPage.routeName: (context) => PopUntilPage(),
ProviderWithFutureBuilderApp.routeName: (context) =>
ProviderWithFutureBuilderApp(),
MediatorPage.routeName: (context) => MediatorPage(),
},
);
}
}
I do not want to use direct widget using home property app. I just want to navigate through only and only using named routes.
Can anyone suggest how to do it properly ?
Thanks.
You need to init SharedPreferences in main() and use WidgetsFlutterBinding.ensureInitialized
You can copy paste run full code below
In demo , I set initScreen to 12
code snippet
int initScreen;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt("initScreen",12);
initScreen = await prefs.getInt("initScreen");
print('initScreen ${initScreen}');
runApp(MyApp());
}
...
initialRoute: initScreen == 0 || initScreen == null
? "/"
: "first",
routes: {
'/': (context) => MyHomePage(title: "demo",),
"first": (context) => FirstPage(),
},
working demo
full code
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
//void main() => runApp(MyApp());
int initScreen;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt("initScreen",12);
initScreen = await prefs.getInt("initScreen");
print('initScreen ${initScreen}');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
initialRoute: initScreen == 0 || initScreen == null
? "/"
: "first",
routes: {
'/': (context) => MyHomePage(title: "demo",),
"first": (context) => FirstPage(),
},
//home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class FirstPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Text("First");
}
}
A simple way to do this is to just use a flag when the load has completed, then, in build:
return _isLoadComplete? MaterialApp() : Container();
Another option, it seems like the MaterialApp is being cached, and initialRoute does not get run the 2nd time. Using a key seems to fix this:
return MaterialApp(
key: UniqueKey(),
//etc
I'd lean towards the first approach, as there's no point having MaterialApp try and show one view, will immediately replacing it with another.

Flutter | How to show AlertDialog on top of any overlay?

How to show AlertDialog always on top of anything on the screen?
Code:
import 'package:flutter/material.dart';
class CountriesField extends StatefulWidget {
#override
_CountriesFieldState createState() => _CountriesFieldState();
}
class _CountriesFieldState extends State<CountriesField> {
final FocusNode _focusNode = FocusNode();
OverlayEntry _overlayEntry;
final LayerLink _layerLink = LayerLink();
#override
void initState() {
_focusNode.addListener(() {
if (_focusNode.hasFocus) {
this._overlayEntry = this._createOverlayEntry();
Overlay.of(context).insert(this._overlayEntry);
} else {
// this._overlayEntry.remove();
}
});
}
OverlayEntry _createOverlayEntry() {
RenderBox renderBox = context.findRenderObject();
var size = renderBox.size;
return OverlayEntry(
builder: (context) => Positioned(
width: size.width,
child: CompositedTransformFollower(
link: this._layerLink,
showWhenUnlinked: false,
offset: Offset(0.0, size.height + 5.0),
child: Material(
elevation: 4.0,
child: ListView(
padding: EdgeInsets.zero,
shrinkWrap: true,
children: <Widget>[
ListTile(
title: Text('Syria'),
onTap: () {
print('Syria Tapped');
},
),
ListTile(
title: Text('Lebanon'),
onTap: () {
print('Lebanon Tapped');
},
)
],
),
),
),
));
}
#override
Widget build(BuildContext context) {
return CompositedTransformTarget(
link: this._layerLink,
child: Material(
child: TextFormField(
focusNode: this._focusNode,
decoration: InputDecoration(labelText: 'Country'),
),
),
);
}
}
class FormPage extends StatefulWidget {
#override
_FormPageState createState() => _FormPageState();
}
class _FormPageState extends State<FormPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Material(elevation: 4.0, child: CountriesField()),
RaisedButton(
child: Text('Help dialog'),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Help"),
content: Text("This should show on top of any overlay"),
actions: <Widget>[
FlatButton(
child: Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
},
)
],
),
);
}
}
There is no easy way to make dialogs appear on top of overlays. Depends on your use case, you can either convert both to Overlay, or convert both to Dialog.
This is an example of converting both to dialogs, using showDialog method:
You don't have to return an AlertDialog widget when showing a dialog, for example, here I'm returning a Container with white filling, and contains a ListView for the "Menu A" dialog in the back.
When using showDialog, you get automatic features such as dimming the background and click anywhere outside to dismiss. If you don't want these or any other dialog things, and if you cannot find a way to disable them easily, you can always go the other way around and convert both to Overlay instead.
For overlays, whichever gets inserted latest, is displayed on top.
This isn't really a "fix", but a potential workaround for this is to basically not use Overlays and rely on a top level Stack.
If you are using Positioned in your Overlay anyway, putting your widget in a top level Stack doesn't interfere with things like Dialogs (and you potentially have more control over which areas of your app show the overlay).
Example:
class StackOverlayState extends State<StackOverlay> {
bool _showOverlay = true; // This could also easily be a list of widgets
Widget build(BuildContext context) {
return Stack(
children: [
Positioned.fill(
child: Scaffold(
body: /// etc..
),
),
if (_showOverlay)
MyOverlayWidget(),
],
);
}
}
I was using Overlays, and switching to just using a Stack instead seems to have caused no issues and required no code changes in the Overlay widget itself, but YMMV.

Flutter, custom scroll effects

I would like to implement a layout like in this video (at 5:50) https://www.youtube.com/watch?v=KYUTQQ1usZE&index=1&list=PL23Revp-82LKxKN9SXqQ5Nxaa1ZpYEQuaadd#t=05m50s
How would you tackle this? I tried with a ListView & GridLayout, but this seems to be limited to archive this. Would I need to use something like CustomMultiChildLayout (https://docs.flutter.io/flutter/widgets/CustomMultiChildLayout-class.html) or maybe a CustomScrollView (https://docs.flutter.io/flutter/widgets/CustomScrollView-class.html)?
Any suggestions would be appreciated, thx :)
Update:
As far as I could find out, I would need to use a CustomScrollView (Correct me if I am wrong). But I am a bit overwhelmed with the options that the Flutter framework leaves me. And I am not sure from the documentation what classes I need to extend or which interfaces I would need to implement to archive my goal. I dont't know how deep I need to dive into the framework. There are the following classes involved when it comes to slivers and lists with custom scroll effects:
RenderSliver This is really the base for render objects which implement scroll effects. I guess it would be overkill to reimplement this. But maybe subclass it and start from there (maybe overkill too)?
RenderSliverMultiBoxAdaptor If we go higher in the hierarchy we find the abstract class RenderSliverMultiBoxAdaptor. A sliver with multiple box children. A RenderSliverBoxChildManager This provides children on the fly for the RenderSliverMultiBoxAdaptor. These are both abstract classes. So maybe start here and extend these classes?
RenderSliverList This extends the RenderSliverMultiBoxAdaptor and provides box children laid out along the main axis. The children are delivered by a class which implement RenderSliverBoxChildManager.
SliverMultiBoxAdaptorElement implements RenderSliverBoxChildManager. So RenderSliverList and SliverMultiBoxAdaptorElement are a concrete implementation of RenderSliverMultiBoxAdaptor and RenderSliverBoxChildManager. I thought that I could extend these classes. But if I do so, I would anyway have to reimplement the performLayout method. So maybe reuse the SliverMultiBoxAdaptorElement and extend RenderSliverMultiBoxAdaptor?
SliverList This class eventually creates the render object (a RenderSliverList with a SliverMultiBoxAdaptorElement as a child manager) and provides a SliverChildDelegate to the SliverMultiBoxAdaptorElement, which in turn lazily builds children for SliverMultiBoxAdaptorWidget. The SliverList places multiple box children in a linear array along the main axis. It uses a class that extends SliverChildDelegate to provide children on the fly. It can be placed inside a CustomScrollViews slivers array. This is the most concrete sliver which creates a list in a CustomScrollView. So could I also archive my goal to have a layout according to the video simply with this? So far I tried to provide the CustomScrollView a ScrollController to intercept the scroll offset and then build the child elements according to the scroll offset and the index of the element with a SliverChildBuilderDelegate. But when doing so, the scrollview does not scroll anymore. It only scrolls, when the total height of all cells exceeds the viewport.
So do I really have to extend RenderSliverMultiBoxAdaptor and implement the perfromLayout method myself? For me it seems to be the only option now...
It's hard to understand slivers logic of from the first look.
But what is important is SliverGeometry class
paintOrigin - think about it as kind of delta y. When you want to make widget
fixed on a screen, you need to push it from the top.
constraints.scrollOffset shows scroll offset of logical place of
widget.
scrollExtent shows logical height of widget. It help widget
to know that you scrolled all slivers.
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey _key = GlobalKey();
RenderObject ansestor;
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback(_getPosition);
super.initState();
}
_getPosition(_) {
setState(() {
ansestor = _key.currentContext.findRenderObject();
});
}
#override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
return CustomScrollView(
physics: ClampingScrollPhysics(),
key: _key,
slivers: <Widget>[
CustomSliver(
isInitiallyExpanded: true,
ansestor: ansestor,
child: _Item(
title: 'first title',
fileName: 'item_1',
),
),
CustomSliver(
ansestor: ansestor,
child: _Item(
title: 'second title',
fileName: 'item_2',
),
),
CustomSliver(
ansestor: ansestor,
child: _Item(
title: 'third title',
fileName: 'item_3',
),
),
CustomSliver(
ansestor: ansestor,
child: _Item(
title: 'fourth title',
fileName: 'item_4',
),
),
CustomSliver(
ansestor: ansestor,
child: _Item(
title: 'fifth title',
fileName: 'item_5',
),
),
CustomSliver(
ansestor: ansestor,
child: _Item(
title: 'first title',
fileName: 'item_6',
),
),
SliverToBoxAdapter(
child: Container(
child: Center(
child: Text('end'),
),
height: 1200,
color: Colors.green.withOpacity(0.3),
),
),
],
);
});
}
}
class CustomSliver extends SingleChildRenderObjectWidget {
CustomSliver({
this.child,
Key key,
this.ansestor,
this.isInitiallyExpanded = false,
}) : super(key: key);
final RenderObject ansestor;
final bool isInitiallyExpanded;
#override
RenderObject createRenderObject(BuildContext context) {
return CustomRenderSliver(
isInitiallyExpanded: isInitiallyExpanded,
);
}
#override
void updateRenderObject(
BuildContext context,
CustomRenderSliver renderObject,
) {
renderObject.ansestor = ansestor;
renderObject.markNeedsLayout();
}
final Widget child;
}
class CustomRenderSliver extends RenderSliverSingleBoxAdapter {
CustomRenderSliver({
RenderBox child,
this.isInitiallyExpanded,
}) : super(child: child);
final double max = 250;
final double min = 100;
RenderObject ansestor;
final bool isInitiallyExpanded;
void performLayout() {
var constraints = this.constraints;
double distanceToTop;
double maxExtent;
if (ansestor != null) {
distanceToTop = child.localToGlobal(Offset.zero, ancestor: ansestor).dy;
}
if (ansestor == null) {
if (isInitiallyExpanded) {
maxExtent = max;
} else {
maxExtent = min;
}
} else {
if (constraints.scrollOffset > 0) {
maxExtent = (max - constraints.scrollOffset).clamp(0.0, max);
} else if (distanceToTop < max) {
maxExtent = min + (3 * (250 - distanceToTop) / 5);
} else {
maxExtent = min;
}
}
child.layout(
constraints.asBoxConstraints(maxExtent: maxExtent),
parentUsesSize: true,
);
var paintExtent = math.min(maxExtent, constraints.remainingPaintExtent);
geometry = SliverGeometry(
paintOrigin: maxExtent == 0 ? 0.0 : constraints.scrollOffset,
scrollExtent: max,
paintExtent: paintExtent,
maxPaintExtent: paintExtent,
hasVisualOverflow: true,
);
constraints = constraints.copyWith(remainingPaintExtent: double.infinity);
setChildParentData(child, constraints, geometry);
}
}
class _Item extends StatelessWidget {
const _Item({
Key key,
#required this.title,
#required this.fileName,
}) : super(key: key);
final String title;
final String fileName;
#override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
return Container(
height: 250,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/$fileName.png'),
fit: BoxFit.fitWidth,
),
),
child: Padding(
padding: const EdgeInsets.only(top: 40),
child: Text(
title,
style: Theme.of(context).textTheme.headline4.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 60,
),
),
),
);
},
);
}
}

Resources