问题描述
如何将动态长文本与另一个小部件(如按钮)一起展开如下:
我尝试了 Expanded
、Flexible
和 Warp
,但没有得出结论。
!注意我不希望它在 Stack
中或从底部使用 Padding
!导致此文本有变化,其长度可能更大或更短。
UPDATE :我尝试使用 ExtendedText,但 TextOverFlowWidget 的子项不显示给我。我的代码:
Container(
color: Colors.Amber,height: 70,child: ExtendedText(
'bbbbb ${toPhonestyle(widget.inputPhone)} (${widget.selectedCountry.dialCode}) aaaaaa aaaaaaaaaaa',overflowWidget: TextOverflowWidget(
// maxHeight: double.infinity,// align: TextOverflowAlign.right,// fixedOffset: Offset.zero,child: Container(
width: 60,height: 60,color: Colors.red,),
但是如果像 height:20
这样缩小 Container 的高度,显示如下:
解决方法
您可以使用一个溢出小部件。
检查他们的例子:
ExtendedText(...
overFlowWidget:
TextOverflowWidget(
//maxHeight: double.infinity,//align: TextOverflowAlign.right,//fixedOffset: Offset.zero,child: Row(
mainAxisSize: MainAxisSize.min,children: <Widget>[
const Text('\u2026 '),RaisedButton(
child: const Text('more'),onPressed: () {
launch(
'https://github.com/fluttercandies/extended_text');
},)
],),...
)
好的,您需要指定 maxLines 才能使溢出正常工作。我认为您正在寻找一个跟随文本的小部件。你可以试试 Text.rich() 小部件
Text.rich(
TextSpan(
text: 'This is an example text!',children: [
WidgetSpan(
// Set the alignment
alignment: PlaceholderAlignment.middle,// You can put any widget inline with text using WidgetSpan
child: Container(
margin: const EdgeInsets.only(left: 8.0),child: ElevatedButton(
child: Text("Read more..."),onPressed: () {},],);
在这种情况下,您不需要扩展文本包。
,显然,您可以使用 RichText
小部件将文本和小部件包装在一行中,即它旨在使用多种显示样式显示文本。文本使用 <TextSpan>
或 <WidgetSpan>
类型的子代呈现。
以下代码将解释您在问题中尝试的确切内容。请注意,我只使用了有状态小部件,因为我也在使用其他东西,所以我只编辑了该小部件中的所有内容,如果您不打算在此处引入任何状态,则可以使用无状态小部件。
完整代码:
import 'package:flutter/material.dart';
void main()
{
runApp(MaterialApp(
home: Home(),));
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final String str = 'Some really long text to show the working of a wrap widget'
+ ' and place a button at the end of the text and it will then prove that'
+ ' you can do the same with other kind of widgets.';
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Container(
width: (MediaQuery.of(context).size.width) / 1.3,decoration: BoxDecoration(
color: Colors.orange[100],child: RichText(
text: TextSpan(
children: [
TextSpan(
text: str,style: TextStyle(
fontSize: 24,color: Colors.black,// treat the child of WidgetSpan as the parameter to insert
// whatever widget you wish to put here
// SizedBox is only used to put a little space after the text string
WidgetSpan(
child: SizedBox(width: 5,WidgetSpan(
child: Container(
child: RaisedButton(
color: Colors.blueAccent,onPressed: (){},child: Text('Button'),]
),);
}
}