我正试图使用函数_get_icons((用Firebase数据库中的数据填充List,但我不知道为什么当函数结束时,List仍然为空(我调用initState((上的函数(。我真的很感激你的帮助!
以下是代码中重要的部分:
class body_get_poducto extends StatefulWidget {
bool isAdmin;
List alergenos = [];
QueryDocumentSnapshot producto;
body_get_poducto({Key? key, required this.producto, required this.isAdmin, required this.alergenos}) : super(key: key);
@override
State<body_get_poducto> createState() => _body_get_poductoState();
}
class _body_get_poductoState extends State<body_get_poducto> {
final firestoreInstance = FirebaseFirestore.instance;
var firebaseUser = FirebaseAuth.instance.currentUser;
@override
void initState() {
_get_icons(widget.producto);
super.initState();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: Column(
children: [
Image.network(
widget.producto.get('imagen'),
height: MediaQuery.of(context).size.height * 0.4,
fit: BoxFit.cover,
),
const SizedBox(height: 16.0 * 1.5),
Container(
padding: const EdgeInsets.fromLTRB(16.0,
16.0 * 2, 16.0, 16.0),
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(12.0 * 3),
topRight: Radius.circular(12.0 * 3),
),
),
child:
Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Row(
children: [
Text(
widget.producto.get('nombre'),
style: Theme.of(context).textTheme.headline6,
),
const SizedBox(width: 16.0),
Text(
"$" + widget.producto.get('precio_estimado').toString(),
style: Theme.of(context).textTheme.headline6,
),
],
),
Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Row(
children: [
Container(
child: Text("Libre de:"),
),
SizedBox(
width: 20,
),
SizedBox(
height: 50,
child:
ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemBuilder: (BuildContext ctx, int index) {
return Image.asset('assets/'+widget.alergenos[index]+'.png', height: 50, width: 50,);
},
itemCount: widget.alergenos.length,
),
)
]),
),
(...)
下面是_get_icons((函数:
void _get_icons(QueryDocumentSnapshot producto) async {
for(var e in producto.get('alergenos')){
await FirebaseFirestore.instance
.collection("Alergenos")
.doc(e)
.get()
.then((value) => widget.alergenos.add(value.get('icono')));
}
widget.alergenos.forEach((element) {print(element);});
}
列表保持为空的原因是在添加值时没有调用setState
。
setState(() => widget.alergenos.add(value.get('icono')))
我会选择您所在州的列表,而不是更改小部件的列表。
我还看到了initState方法的一个问题,您可以从自己的方法开始,但正如文档所提到的,您应该始终从super.initState()
开始。
此方法的实现应该从对继承方法的调用开始,如super.initState((.