import 'package:flutter/material.dart';
void main() {
runApp(const MainApp());
}
class MainApp extends StatelessWidget {
const MainApp({super.key});
Future<void> _initialize() async {
await Future.delayed(const Duration(seconds: 2));
try {
throw Exception("Error");
} catch (e) {}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: FutureBuilder(
future: _initialize(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const Text(snapshot.error.toString());
}
return const Text("Completed");
}
return const CircularProgressIndicator();
},
),
),
);
}
}
In this code I am trying to display the error inside the FutureBuilder. If handle the error with a try catch statement, the future is completed with no errors, but If don’t, the app crashes. How can I make the FutureBuilder aware of the error?
2
Answers
note:
Future<void>
is not return any value. If you still use it, thesnapshot.data
will always null.Future.builder
will catch any error when the future function throw any exception.Try return
Future.error("Error")
when you catch an error.