我试图学习一些flutter编程,但我遇到了一个问题,当我运行程序时,我第一次没有在屏幕上获得信息,我的意思是数据是从firestore检索的,但我必须多次重新加载页面才能在屏幕上显示数据,可能会发生什么情况我使用的是FutureBuilder
- pet_页面.dart*
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:histovet/src/controller/pet_controller.dart';
import 'package:histovet/src/models/pet_model.dart';
import 'package:histovet/src/pages/widgets/menu_lateral.dart';
import 'package:histovet/src/pages/pet/add_pets.dart';
import 'package:histovet/src/pages/pet/pet_update.dart';
// Clases encargadas de la vista donde se enlistan todas las ventas que existan en la
// base de datos
class PetsPage extends StatefulWidget {
static String id = "pets_page";
const PetsPage({Key? key}) : super(key: key);
@override
State<PetsPage> createState() => _PetsPageState();
}
class _PetsPageState extends State<PetsPage> {
TextStyle txtStyle = const TextStyle(
fontWeight: FontWeight.w900, fontSize: 30, color: Colors.black);
PetController petCont = PetController();
bool answer = false;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text("Mascotas"),
actions: [
IconButton(
onPressed: () {
setState(() {});
},
icon: const Icon(Icons.refresh))
],
),
//drawer: const MenuLateral(),
floatingActionButton: FloatingActionButton.extended(
icon: const Icon(FontAwesomeIcons.plus),
label: const Text('Registrar nueva mascota'),
elevation: 15.0,
backgroundColor: Colors.blue,
onPressed: () {
Navigator.pushNamed(context, AddPet.id);
}),
body: FutureBuilder(
future: petCont.allPets(),
builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
if (snapshot.hasError) {
print("error");
return const Text('Error');
} else if (snapshot.hasData) {
List species = snapshot.data ??[];
print(species);
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListView(
children: [
for (Pet specie in species)
Card(
margin: const EdgeInsets.all(6),
elevation: 6,
child: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/img/fondo.jpg'),
fit: BoxFit.cover,
opacity: 0.3),
),
child: ListTile(
onLongPress: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UpdatePet(
specie.id.toString(),
specie.owner.toString())));
},
leading: const Icon(
FontAwesomeIcons.paw,
color: Colors.black,
),
title: Text(
specie.name,
style: txtStyle,
),
subtitle: Text(
specie.specie,
style: txtStyle.copyWith(fontSize: 17),
),
trailing: IconButton(
icon: const Icon(Icons.delete,
color: Colors.black),
onPressed: () {
messageDelete(specie.id.toString());
Navigator.pushNamed(context, '/pets')
.then((_) => setState(() {}));
},
))),
)
],
),
);
} else {
return const Text('Empty data');
}
})),
);
}
// Le indica al usuario si se pudo o no eliminar el registro
void messageDelete(String idPet) async {
answer = await petCont.deletePet(idPet);
if (answer) {
Navigator.pushNamed(context, '/pets').then((_) => setState(() {}));
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Se eliminó el registro de la mascota"),
backgroundColor: Colors.green,
));
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("No se pudo eliminar el registro de la mascota"),
backgroundColor: Colors.green,
));
}
}
}
- pet_控制器.dart*
Future<List<Pet>> allPets() async {
try{
_pets = await _service.getPetsBD();
return _pets;
} catch (e) {
return _pets;
}
}
- 宠物_服务.dart*
Future<List<Pet>> getPetsBD() async {
List<Pet> mascotas = [];
final FirebaseAuth auth = FirebaseAuth.instance;
final User? user = auth.currentUser;
final uid = user?.uid;
try {
final collection = FirebaseFirestore.instance
.collection('pets')
.where('owner', isEqualTo: uid);
collection.snapshots().listen((querySnapshot) {
for (var doc in querySnapshot.docs) {
Map<String, dynamic> data = doc.data();
Pet newPet = Pet(
data["id"],
data["owner"],
data["birthday"].toString(),
data["name"],
data["neutering"],
data["age"],
data["breed"],
data["specie"],
data["color"],
data["gender"],
data["clinic"]);
mascotas.add(newPet);
}
});
return mascotas;
} catch (e) {
return mascotas;
}
}
2条答案
按热度按时间ppcbkaq51#
请尝试;
至
5tmbdcev2#
当新数据可用时,FutureBuilder小部件似乎没有被重建。这可能是因为petCont.allPets()返回的Future没有改变。
您可以在每次重新构建部件时向FutureBuilder提供一个新的Future来解决这个问题。例如,您可以使用StatefulWidget并将Future存储在部件的状态中。然后,在build方法中,您可以在每次重新构建部件时返回一个新的FutureBuilder,其中包含更新的Future。这将导致FutureBuilder重新构建并显示更新的数据。
下面是一个如何实现这一点的示例:
在上面的代码中,petCont.allPets()返回的Future存储在StatefulWidget的状态中,并在build方法中返回一个新的FutureBuilder
我希望这是有用的,看看我的生物!