FutureBuilder Good Example 1
FutureBuilder Good Example 1
dart';
void main() {
runApp(const MaterialApp(home: HomePage()));
}
Future<String> getWriterName() {
return Future.delayed(const Duration(seconds: 3), () => "Maria Elijah");
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.deepPurpleAccent,
title: const Text('Flutter FutureBuilder'),
),
body: SizedBox(
width: double.infinity,
child: Center(
child: FutureBuilder(
future: getWriterName(),
initialData: "Code sample",
builder: (BuildContext context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(
color: Colors.deepPurpleAccent,
),
);
}
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Center(
child: Text(
'An ${snapshot.error} occurred',
style: const TextStyle(fontSize: 18, color: Colors.red),
),
);
} else if (snapshot.hasData) {
final data = snapshot.data;
return Center(
child: Text(
data!,
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
);
}
}