FutureBuilder trong Flutter
Xin chào, người đam mê rung động!
Hôm nay chúng ta sẽ tìm hiểu thêm về cách hiển thị dữ liệu không đồng bộ một cách chính xác từ Future<T>trong FutureBuilderrung.
Chúng ta đều biết, Future<T>thật tuyệt vời. Nó cho phép chúng tôi thực hiện công việc không đồng bộ như tìm nạp dữ liệu từ máy chủ mà không cần suy nghĩ Threads và Deadlockstất cả.
Future<Model> _doCalculation() async {
// do calculation / computation asynchronously.
....
return Model;
}
FutureBuilder<Model>(
future: _doCalculationFuture,
builder: (BuildContext context, AsyncSnapshot<Model> snapshot) {
if (snapshot.hasData) {
return DataWidget(snapshot.requireData);
} else if (snapshot.hasError) {
return ErrorWidget();
} else {
return CircularProgressIndicator();
}
return const SizedBox();
},
);
Chúng ta phải cẩn thận khi cung cấp Future<T>Vì FutureBuilder.ý FutureBuilderchí thường nằm bên trong buildphương thức và chúng ta biết buildphương thức có thể được gọi nhiều lần, nên chúng ta không được tạo Future<T>bên trong nó.
Nếu chúng ta tạo phương thức Future<T>bên trong build, nó sẽ được tạo lại bất cứ khi nào buildđược gọi. Nó có thể không phải là những gì bạn muốn.
Vậy tạo ở đâufutures?
Nơi lý tưởng để tạo hoặc cập nhật tương lai là các phương thức vòng đời của tiện ích con, chẳng hạn như initState, didUpdateWidget, didChangeDependenciesv.v. hoặc bất kỳ nơi nào khác ngoàibuild.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
late Future<Model> _doCalculationFuture;
@override
void initState() {
super.initState();
_doCalculationFuture = _doCalculation();
}
Future<Model> _doCalculation() async {
return await Future<Model>.delayed(
const Duration(seconds: 2),
() => Model(),
);
}
@override
Widget build(BuildContext context) {
return FutureBuilder<Model>(
future: _doCalculationFuture,
builder: (BuildContext context, AsyncSnapshot<Model> snapshot) {
if (snapshot.hasData) {
return DataWidget(snapshot.requireData);
} else if (snapshot.hasError) {
return ErrorWidget();
} else {
return CircularProgressIndicator();
}
return const SizedBox();
},
);
}
}
Chúc mừng mã hóa!!

![Dù sao thì một danh sách được liên kết là gì? [Phần 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































