setState应该在哪里调用?



我正在尝试创建一个自定义导航栏,并控制与_current显示的内容,当我更新_current时,我不运行setState,因为显示器上没有任何变化(我认为这是正确的逻辑?显示的方块应该是从数组中挑选出来的。下面的代码是我所拥有的,这是一个setState问题还是别的什么?

import 'package:flutter/material.dart';
class CustomNav extends StatefulWidget {
const CustomNav({Key? key}) : super(key: key);
@override
_CustomNavState createState() => _CustomNavState();
}
class _CustomNavState extends State<CustomNav> {
@override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
int _current = 1;
List<Widget> pages = [
Container(
color: Colors.white,
width: 50,
height: 50,
),
Container(
color: Colors.yellow,
width: 50,
height: 50,
),
Container(
color: Colors.green,
width: 50,
height: 50,
)
];
return Container(
color: Colors.blue,
width: width,
height: 100,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
pages[_current],
IconButton(
onPressed: () {
_current = 0;
print({_current});
},
icon: Icon(Icons.ac_unit)),
IconButton(
onPressed: () {
_current = 1;
print({_current});
},
icon: Icon(Icons.ac_unit)),
IconButton(
onPressed: () {
_current = 2;
print({_current});
},
icon: Icon(Icons.ac_unit))
],
),
);
}
}

不能在build方法中添加_current。事实上,您应该尽量不要在构建方法中添加任何东西。从构建方法中取出_current。然后,如果_current对UI组件有影响,当你更新它时,你必须把它放在setState中。

每次更改_current时,都需要调用setState。这是因为您需要通知CustomNav小部件,它需要重新构建自己。

最新更新