added layoutbuilder to optimize code and simplify logic

This commit is contained in:
ryg-git 2021-02-06 18:18:54 +05:30
parent 5bde6a4e51
commit d822887ea5
1 changed files with 50 additions and 65 deletions

View File

@ -99,39 +99,11 @@ class PostWidget extends HookWidget {
); );
} }
List<ui.LineMetrics> postNeedsToTruncate(
String body,
Size size,
ui.TextDirection textDirection,
) {
final span = TextSpan(
text: body,
);
final tp = TextPainter(
text: span,
maxLines: 20,
textDirection: textDirection,
)..layout(maxWidth: size.width - 20);
return tp.computeLineMetrics();
}
// == UI == // == UI ==
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final textPostData = post.post.body == null
? []
: postNeedsToTruncate(
post.post.body,
MediaQuery.of(context).size,
Directionality.of(context),
);
final textPostLineHeight = textPostData.isNotEmpty
? (textPostData.first as ui.LineMetrics).height
: 0.0;
void _openLink() => linkLauncher( void _openLink() => linkLauncher(
context: context, url: post.post.url, instanceHost: instanceHost); context: context, url: post.post.url, instanceHost: instanceHost);
@ -455,16 +427,21 @@ class PostWidget extends HookWidget {
padding: const EdgeInsets.all(10), padding: const EdgeInsets.all(10),
child: child:
MarkdownText(post.post.body, instanceHost: instanceHost)), MarkdownText(post.post.body, instanceHost: instanceHost)),
if (post.post.body != null && if (post.post.body != null && !fullPost)
!fullPost && LayoutBuilder(
textPostData.length <= 20) builder: (context, constraints) {
Padding( final span = TextSpan(
padding: const EdgeInsets.all(10), text: post.post.body,
child: );
MarkdownText(post.post.body, instanceHost: instanceHost)), final tp = TextPainter(
if (post.post.body != null && !fullPost && textPostData.length > 20) text: span,
Container( maxLines: 20,
constraints: BoxConstraints(maxHeight: textPostLineHeight * 20), textDirection: Directionality.of(context),
)..layout(maxWidth: constraints.maxWidth - 20);
if (tp.didExceedMaxLines) {
return Container(
constraints: BoxConstraints(maxHeight: tp.height),
child: Stack( child: Stack(
alignment: Alignment.bottomCenter, alignment: Alignment.bottomCenter,
children: [ children: [
@ -479,7 +456,7 @@ class PostWidget extends HookWidget {
), ),
), ),
Container( Container(
height: textPostLineHeight * 4, height: tp.preferredLineHeight * 4,
decoration: BoxDecoration( decoration: BoxDecoration(
gradient: LinearGradient( gradient: LinearGradient(
begin: Alignment.topCenter, begin: Alignment.topCenter,
@ -493,6 +470,14 @@ class PostWidget extends HookWidget {
), ),
], ],
), ),
);
} else {
return Padding(
padding: const EdgeInsets.all(10),
child: MarkdownText(post.post.body,
instanceHost: instanceHost));
}
},
), ),
actions(), actions(),
], ],