1 | initial version |
Here are the steps to implement a FutureBuilder
on an onTap
function in Flutter:
Define a Future
variable that represents the asynchronous operation you want to perform when the onTap
event occurs.
Wrap the code that performs this operation in a Future
function, which will return the result of the operation as a Future
.
In the onTap
function, use a FutureBuilder
widget to wait for the completion of the Future
operation and display the result.
Here's an example:
class MyApp extends StatelessWidget {
Future<String> _loadData() async {
// Perform some asynchronous operation and return result.
return Future.delayed(Duration(seconds: 2), () => "Hello, World!");
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("My App"),
),
body: GestureDetector(
onTap: () {
// Display result of _loadData() in a dialog.
showDialog(
context: context,
builder: (BuildContext context) {
return FutureBuilder<String>(
future: _loadData(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Text("Error: ${snapshot.error}");
} else {
return Text("Result: ${snapshot.data}");
}
} else {
return CircularProgressIndicator();
}
},
);
},
);
},
child: Center(
child: Text("Tap to load data..."),
),
),
),
);
}
}
In this example, _loadData()
is a hypothetical function that performs some asynchronous operation and returns a Future
with a String
value. When the user taps the screen, the onTap
function displays the result of _loadData()
in a dialog box using a FutureBuilder
widget.
The FutureBuilder
widget is configured with the future
property set to _loadData()
. The builder
function is used to display the result of the operation when it completes. The snapshot
object contains information about the state of the Future
operation, including whether it is still in progress (ConnectionState.waiting
) or has completed (ConnectionState.done
).
If the operation has completed successfully, the snapshot
object contains the data returned by _loadData()
, which can be accessed using snapshot.data
. If the operation has failed, snapshot.hasError
will be true
, and the error message can be accessed using snapshot.error
. While the operation is still in progress, a CircularProgressIndicator
is displayed.