Created
January 11, 2020 06:30
-
-
Save vovahost/2d555ca371c08758c8b2d7725f3bd19d to your computer and use it in GitHub Desktop.
Listen for widget size changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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