【发布时间】:2019-06-16 20:41:43
【问题描述】:
我有一个底部导航栏,它使用此代码来切换小部件:
void _onItemTapped(int index) {
setState(() {
selectedIndexGlobal = index;
print(index);
});
}
并在正文中显示所需的小部件:
body: SafeArea(
child: new LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
Container con = Container(
child: _widgetOptions.elementAt(selectedIndexGlobal)
);
return con;
}
))
我还有一个从 Firebase 加载的带有静态子列表的 GridView,并尝试对其应用 GestureDetector,以更改 selectedIndex 并更新屏幕状态:
static getExpenseItems(AsyncSnapshot<QuerySnapshot> snapshot, BuildContext context) {
try {
snapshot.data.documents.sort((a, b) =>
a.data["order"].compareTo(b.data["order"]));
} on NoSuchMethodError {}
return snapshot.data.documents
.map((doc) =>
new GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
catName = doc["catName"];
setState(() {
selectedIndexGlobal = 4;
});
},
child: new Container(
child: Container(
padding: EdgeInsets.only(top: 15, left: 10, bottom: 15),
decoration: new BoxDecoration(
border: new Border.all(color: Colors.grey[200],
width: 0.8)),
child: Align(
alignment: Alignment.centerLeft,
child: Text(doc["name"],
style: TextStyle(fontSize: categoriesFont),
textAlign: TextAlign.center),
)
)
)
)
).toList();
}
但是 setState 不能从静态方法中调用,而且 GridView.count 不允许我将非静态小部件用作子小部件。那么我应该怎么做才能更新点击状态?
【问题讨论】:
-
为什么不去掉 static 关键字?
-
您也许可以将“回调”传递给从外部更新状态的静态函数。
-
@nonybrighto GridView 只接受静态子列表
-
@Martin Niederl 你能举个例子吗?
-
我有同样的问题有什么想法吗?
标签: flutter