FutureBuilder with ListView in Flutter
This blog post is an example of displaying data from a FutureBuilder to a ListView widget in Flutter. The FutureBuilder widget allows you to build futuristic user interfaces that are responsive and performant.
ListView is a scrolling widget that allows us to create a scrollable list of items. In order to use the ListView widget, you need to have a collection of items to display. In this case, we’re going to use a FutureBuilder to get data from an API and display it in a ListView.
class PickingPage extends StatefulWidget {
final StockPicking? picking;
const PickingPage(this.picking, {Key? key}) : super(key: key);
@override
_PickingPageState createState() => _PickingPageState();
}
class _PickingPageState extends State<PickingPage> {
Future<List<StockMove>?>? _futureStockMoves;
@override
void initState() {
super.initState();
//fetch stock moves on loading
_futureStockMoves = _fetchStockMoves();
}
Future<List<StockMove>?> _fetchStockMoves() async {
StockMoveResponse response =
await _odooStockMove.searchByIds(widget.picking!.move_lines!);
return response.stockMoves!;
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<StockMove>?>(
future: _futureStockMoves,
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const ErrorText();
} else if (snapshot.hasData) {
final moves = snapshot.data as List<StockMove>;
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if(widget.picking!.picker_release!)
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
TextButton(onPressed: (){
setState(() {
});
}, child: const Text("Press Me", style:TextStyle(color: MyTheme.highlightColor),))
],),
if (moves.isNotEmpty)
...moves
.map((item) => Text(item.name))
else
const Text('No product')
],
);
}
}
// Displaying LoadingSpinner to indicate waiting state
return CenterProgressIndicator();
}
);
}
}