skip to Main Content
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


  1. note: Future<void> is not return any value. If you still use it, the snapshot.data will always null.


    Future.builder will catch any error when the future function throw any exception.

    void main() {
      runApp(const MainApp());
    }
    
    class MainApp extends StatelessWidget {
      const MainApp({super.key});
    
      Future<String> _initialize() async {
        await Future.delayed(const Duration(seconds: 2));
        try {
          // call your function here
          // for example this method will return String complete
          return Future.value("Complete");
        }  on TimeoutException catch(e) {
          throw ("Time out broo....!$e"); // you can throw custom message
          
        } catch (e) {
          rethrow; // this is will throw any error message;
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: Center(
              child: FutureBuilder<String>(
                future: _initialize(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    if (snapshot.hasError) {
                      return Text(snapshot.error.toString());
                    } else if (snapshot.hasData) {
                      return Text(snapshot.data!); 
                    }
                  }
                  return const CircularProgressIndicator();
                },
              ),
            ),
          ),
        );
      }
    }
    
    
    Login or Signup to reply.
  2. Try return Future.error("Error") when you catch an error.

      Future<void> _initialize() async {
        await Future.delayed(const Duration(seconds: 2));
        try {
          throw Exception("Error");
        } catch (e) {
          return Future.error("Error");
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search