Skip to content

Instantly share code, notes, and snippets.

@vovahost
Created January 11, 2020 06:30
Show Gist options
  • Save vovahost/2d555ca371c08758c8b2d7725f3bd19d to your computer and use it in GitHub Desktop.
Save vovahost/2d555ca371c08758c8b2d7725f3bd19d to your computer and use it in GitHub Desktop.
Listen for widget size changes.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
/// There's an alternative and better way to achieve this by using RenderObject / CustomMultiChildLayout but I will not cover it here.
class MyTextInput extends StatefulWidget {
@override
_MyTextInputState createState() => _MyTextInputState();
}
class _MyTextInputState extends State<MyTextInput> {
final ValueNotifier<double> _scrollViewPaddingNotifier = ValueNotifier(0);
final GlobalKey _textFieldKey = GlobalKey();
@override
void initState() {
SchedulerBinding.instance.addPostFrameCallback((_) {
_updateScrollViewPadding();
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
ValueListenableBuilder<double>(
valueListenable: _scrollViewPaddingNotifier,
builder: (BuildContext context, double paddingBottom, Widget child) {
print('ScrollView padding: $paddingBottom');
return ListView(
reverse: true,
children: [
Text('item 0'),
Text('item 1'),
Text('item 2'),
],
padding: EdgeInsets.only(bottom: paddingBottom),
);
},
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Container(
color: Colors.greenAccent.withOpacity(0.5),
child: NotificationListener<SizeChangedLayoutNotification>(
onNotification: (notification) {
print('notification: $notification');
_updateScrollViewPadding();
return true;
},
child: SizeChangedLayoutNotifier(
child: TextField(
key: _textFieldKey,
decoration: InputDecoration(
hintText: 'Type something...',
isDense: true,
border: InputBorder.none,
),
maxLines: 4,
minLines: 1,
),
),
),
),
],
),
],
),
);
}
void _updateScrollViewPadding() {
final height = _textFieldKey.currentContext.size.height;
SchedulerBinding.instance.addPostFrameCallback((_) {
_scrollViewPaddingNotifier.value = height;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment