如何解决使用 widget.[variable_name] 是引用 StatefulWidget 变量的最佳方式吗?
我有一个传递给 FriendsFeed 类的变量 friendsList
。我用 friendsList
引用 FriendsFeed 状态中的 widget.friendsList
。使用 widget.[my_variable_name]
来引用 StatefulWidget 变量是一种专业的方式吗?我不禁觉得有一种更简洁的方法可以做到这一点。
import 'package:Flutter/material.dart';
class FriendsFeed extends StatefulWidget {
FriendsFeed(this.friendsList);
final List<dynamic> friendsList;
@override
_FriendsFeedState createState() => _FriendsFeedState();
}
class _FriendsFeedState extends State<FriendsFeed> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final Color oddItemColor = colorScheme.primary.withOpacity(0.05);
final Color evenItemColor = colorScheme.primary.withOpacity(0.15);
return ReorderableListView(
padding: const EdgeInsets.symmetric(horizontal: 40),children: <Widget>[
for (int index = 0; index < widget.friendsList.length; index++)
ListTile(
key: Key('$index'),tileColor:
widget.friendsList[index].isOdd ? oddItemColor : evenItemColor,title: Text('Item ${widget.friendsList[index]}'),),],onReorder: (int oldindex,int newIndex) {
setState(() {
if (oldindex < newIndex) {
newIndex -= 1;
}
final int item = widget.friendsList.removeAt(oldindex);
widget.friendsList.insert(newIndex,item);
});
},);
}
}
解决方法
是的,是的。但您仍然可以通过一些方法使其更干净。
一种方法是在 build 方法中创建一个 final 变量,或者作为应用程序中的 final 字段,比如“friendList”,然后将其赋值为“widget.friendsList”。您现在可以继续在构建函数或应用中的任何位置使用 var "friendList"(取决于您声明它的位置)。
因此,从您的代码看来,您似乎希望能够重新排序/重新排列列表中的项目,这意味着能够修改列表,我建议您像这样在状态类中创建一个字段:
class FriendsFeed extends StatefulWidget {
FriendsFeed(this.friendsList);
final List<dynamic> friendsList;
@override
_FriendsFeedState createState() => _FriendsFeedState();
}
class _FriendsFeedState extends State<FriendsFeed> {
// declare it here if you wish to make any modification to the list
// outside the build function.
late List<dynamic> _friendsList;
@override
void initState() {
_friendsList = widget.friendsList;
super.initState();
}
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final Color oddItemColor = colorScheme.primary.withOpacity(0.05);
final Color evenItemColor = colorScheme.primary.withOpacity(0.15);
return ReorderableListView(
padding: const EdgeInsets.symmetric(horizontal: 40),children: <Widget>[
for (int index = 0; index < _friendsList.length; index++)
ListTile(
key: Key('$index'),tileColor: _friendsList[index].isOdd ? oddItemColor : evenItemColor,title: Text('Item ${_friendsList[index]}'),),],onReorder: (int oldIndex,int newIndex) {
setState(() {
if (oldIndex < newIndex) {
newIndex -= 1;
}
final int item = _friendsList.removeAt(oldIndex);
_friendsList.insert(newIndex,item);
});
},);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。