我有一个底部导航栏,该导航栏使用以下代码来切换小部件:
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不允许我将非静态小部件用作子级。那我该怎么做才能更新点击状态?
答案 0 :(得分:3)
此行将帮助您获取所需的Widget State对象的实例。
您需要访问的是当前上下文对象:
_HomeState stateObject = context.findAncestorStateOfType<_HomeState>();
stateObject.setState(() {
_tabIndex = index;
});
为此,请确保用于访问“状态对象”的上下文来自您要查找的“状态”对象的子小部件。