更新列表视图中标题的文本 [英] Update text of title in a listview
问题描述
我有一个带有ListTiles的列表视图,并且我想更改onTap方法上的标题文本.这是我尝试过的:
I have a listview with ListTiles in it and I want to change title text on onTap method. Here's what I've tried:
body: ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
//My thought was to use a variable to hold a reference to the Text widget
var title = Text(
'Old text',
overflow: TextOverflow.ellipsis,
maxLines: 1,
);
return ListTile(
leading: Icon(Icons.android),
title: title,
onTap: () => setState(
() => {
title = Text(//here I assign a new reference with the new value
'New text',
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
},
),
subtitle: Text(
'Subtitle text',
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
trailing: Icon(
Icons.android,
),
);
},
),
我尝试搜索解决方案,但未成功...
I tried to search a solution but unsuccessful...
我该怎么做?
推荐答案
如果在包含许多后代的小部件中使用 setState()
,则会导致所有后代的重建.应用的性能.最好仅在树的叶子小部件中使用它.更好的方法是将孩子分为StatefulWidget类,如下所示.
If you use setState()
in a widget which has lots of descendants, it causes rebuilds of all of them and can affect the performance of the app. It is better to use it only in leaf widgets of the tree. A better approach is to separate the child into a StatefulWidget class as below.
或者,最好使用其他方法,例如 ChangeNotifierProvider 或BLoC模式.
Or, it'll be good to use other approaches like ChangeNotifierProvider or the BLoC pattern.
以下是使用setState()的示例.
Here is an example using setState().
body: ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return _MyListTile(
title: 'Old text',
subTitle: 'Subtitle text',
);
},
),
class _MyListTile extends StatefulWidget {
const _MyListTile({this.title, this.subTitle});
final String title;
final String subTitle;
@override
_MyListTileState createState() => _MyListTileState();
}
class _MyListTileState extends State<_MyListTile> {
String _title;
@override
void initState() {
super.initState();
_title = widget.title;
}
@override
Widget build(BuildContext context) {
return ListTile(
leading: Icon(Icons.android),
title: Text(_title),
onTap: () => setState(
() => _title = 'New text',
),
subtitle: Text(
widget.subTitle,
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
trailing: Icon(
Icons.android,
),
);
}
}
这篇关于更新列表视图中标题的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!