【发布时间】:2021-09-19 11:33:32
【问题描述】:
我是 Flutter/Dart 开发的新手,但我遇到了调用 setState 不会重建小部件的问题。
我试图在 UI 中显示用户在点击它们以及将它们添加到另一个列表时选择的类型。重新打开模式时,点击选择的颜色应该会发生变化,但没有任何变化,但流派实际上已添加到另一个列表中。
这是代码
class GenresPicker extends StatefulWidget {
@override
_GenresPickerState createState() => _GenresPickerState();
}
class _GenresPickerState extends State<GenresPicker> {
List<Genre> _selectedGenres = [];
@override
void initState() {
super.initState();
}
addGenre(genre) {
setState(() {
_selectedGenres.add(genre);
});
}
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
padding: EdgeInsets.all(20),
child: FutureBuilder<List<Genre>>(
future: fetchGenres(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Container(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"MODAL BOTTOM SHEET EXAMPLE",
style: TextStyle(
fontStyle: FontStyle.italic,
letterSpacing: 0.4,
fontWeight: FontWeight.w600),
),
SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () {
showModalBottomSheet(
context: context,
builder: (context) {
return Column(
children: <Widget>[
Text("Genres:"),
Expanded(
child: GridView.builder(
gridDelegate:
SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 100,
childAspectRatio: 4 / 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10),
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext ctx, index) {
return Container(
alignment: Alignment.center,
child: GestureDetector(
onTap: () {
//_selectedGenres
// .add(snapshot.data![index]);
if (!_selectedGenres.contains(
snapshot.data![index])) {
addGenre(snapshot.data![index]);
}
},
child: Text(snapshot.data![index].name),
),
decoration: BoxDecoration(
color: _selectedGenres.contains(
snapshot.data![index])
? Colors.blue[200]
: Colors.blue[50],
borderRadius:
BorderRadius.circular(15)),
);
},
),
),
],
);
},
);
},
child: Text(
'Click Me',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
letterSpacing: 0.6),
),
),
],
),
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return Center(child: CircularProgressIndicator());
},
),
);
}
}
注释的代码是一种解决方法,它在某种程度上工作得更好,但不是预期的结果,因为当点击并重新打开模式时,实际显示了选择。
提前致谢。
【问题讨论】: