gpt4 book ai didi

flutter - Flutter:在其他有状态的小部件中更新字符串

转载 作者:行者123 更新时间:2023-12-03 03:57:26 25 4
gpt4 key购买 nike

我正在使用全状态窗口小部件来处理文本的长度。 (显示更多,显示更少)

class DescriptionTextWidget extends StatefulWidget {
final String text;

DescriptionTextWidget({@required this.text});

@override
_DescriptionTextWidgetState createState() =>
new _DescriptionTextWidgetState();
}

class _DescriptionTextWidgetState extends State<DescriptionTextWidget> {
String firstHalf;
String secondHalf;

bool flag = true;

@override
void initState() {
super.initState();

if (widget.text.length > 400) {
firstHalf = widget.text.substring(0, 400);
secondHalf = widget.text.substring(400, widget.text.length);
} else {
firstHalf = widget.text;
secondHalf = "";
}
}


@override
Widget build(BuildContext context) {
return new Container(
padding: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
child: secondHalf.isEmpty
? new Text(firstHalf, style: TextStyle(color: Colors.white))
: new Column(
children: <Widget>[
new Text(
flag ? (firstHalf + "...") : (firstHalf + secondHalf),
style: TextStyle(color: Colors.white),
),
new InkWell(
splashColor: Colors.transparent,
child: new Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
new Text(
flag ? "show more" : "show less",
style:
new TextStyle(color: Colors.white.withOpacity(0.8)),
),
],
),
onTap: () {
setState(() {
flag = !flag;
});
},
),
],
),
);
}
}

在我的主类中:我将文本“给”这个完整的小部件,如下所示:
 GestureDetector(
onTap: () async {

},
child: DescriptionTextWidget(
text: myString,
),

如果我在主要的全状态小部件中更新了myString,则在全状态小部件'DescriptionTextWidget'中不会更新字符串。

更新DescriptionTextWidget类中的String的最佳方法是什么?

提前致谢!

最佳答案

Sample on DartPad

class DescriptionTextWidget extends StatefulWidget {
final ValueNotifier<String> text;
}

class _DescriptionTextWidgetState extends State<DescriptionTextWidget> {
@override
void initState() {
super.initState();
widget.text.addListener(() => setState(initText));
initText();
}

initText() {
if (widget.text.value.length > 400) {
firstHalf = widget.text.value.substring(0, 400);
secondHalf = widget.text.value.substring(400, widget.text.value.length);
} else {
firstHalf = widget.text.value;
secondHalf = "";
}
}
}

主类:
ValueNotifier<String> myString;

updateString(String value){
myString.value = value;
}

关于flutter - Flutter:在其他有状态的小部件中更新字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59918796/

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