gpt4 book ai didi

flutter - 如何限制 TextSpan 小部件的文本长度

转载 作者:IT王子 更新时间:2023-10-29 07:10:26 25 4
gpt4 key购买 nike

我是 Flutter 的新手。使用 TextSpan 小部件时如何限制文本?

我的代码

Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Row(
children: <Widget>[
Expanded(
flex: 2,
child: Row(
children: <Widget>[
Stack(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(8)),
child: Image.asset(
lastPlayedGame.imagePath,
height: 60,
width: 45,
fit: BoxFit.cover,
),
),
Positioned(
left: 8,
right: 8,
top: 0,
bottom: 0,
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
),
child: Icon(
Icons.play_arrow,
color: Colors.red,
),
),
),
],
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: RichText(
text: TextSpan(children: [
TextSpan(text: lastPlayedGame.name, style: headingTwoTextStyle,),
TextSpan(text: '\n'),
TextSpan(text: "${lastPlayedGame.hoursPlayed} hours played", style: bodyTextStyle),
]),
),
)
],
),
),
Expanded(
child: GameProgressWidget(screenWidth: screenWidth, gameProgress: gameProgress),
),
],
),
);
}
}

在我的 Android 设备上运行时,出现错误:

A RenderFlex overflowed by 15 pixels on the right.

enter image description here

如何限制文本长度?也许检查文本是否是屏幕的最大值,将显示 Assasin's Creed...(可能有点?)

最佳答案

如果您想使用您的 RichText Row 内的小部件并用省略号防止溢出,你首先必须将它包裹在 Flexible 中. Flexible表示RichText可以收缩的Row

RichText 包装在 Flexible 之后,只需将 overflow: TextOverflow.ellipsis 添加到您的 RichText 即可。这是一个最小的例子,在 Row 内的 Flexible 内有一个 RichText

Demo

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Container(
padding: EdgeInsets.all(4.0),
color: Colors.lime,
width: 200.0,
child: Row(
children: <Widget>[
Flexible(
child: RichText(
overflow: TextOverflow.ellipsis,
strutStyle: StrutStyle(fontSize: 12.0),
text: TextSpan(
style: TextStyle(color: Colors.black),
text: 'A very long text :)'),
),
),
Container(
width: 100.0,
height: 100.0,
color: Colors.orangeAccent,
)
],
),
)),
),
);
}
}

关于flutter - 如何限制 TextSpan 小部件的文本长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57685855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com