Search code examples
flutter

How does the Flutter framework handle asynchronous programming,


How does the Flutter framework handle asynchronous programming, and what is the role of the FutureBuilder widget in this context?

I'm new into flutter and I don't have any idea can someone help me this???

you can also give me some example regarding this.


Solution

  • Flutter handles asynchronous programming using Dart's Future and Stream classes. These are part of Dart's async library, which enables non-blocking, asynchronous operations such as fetching data from the network, reading files, or performing complex computations without freezing the UI.

    Futures represent a potential value or error that will be available at some point in the future. They are commonly used for single asynchronous computations. A Future can be in one of three states: uncompleted, completed with a value, or completed with an error. Dart provides various methods and keywords like async, await, then, and catchError to work with futures.

    Streams represent a sequence of asynchronous events. They are useful for handling multiple events over time, such as data received from a WebSocket connection, user interactions, or periodic timer events.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('FutureBuilder Example'),
            ),
            body: Center(
              child: RandomDataWidget(),
            ),
          ),
        );
      }
    }
    
    class RandomDataWidget extends StatelessWidget {
      // Simulate a network call or a long-running operation
      Future<String> fetchRandomData() async {
        await Future.delayed(Duration(seconds: 2));
        return "Random Data Loaded";
      }
    
      @override
      Widget build(BuildContext context) {
        return FutureBuilder<String>(
          future: fetchRandomData(),
          builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
            // Checking the state of the Future
            if (snapshot.connectionState == ConnectionState.waiting) {
              return CircularProgressIndicator(); // Show a loading spinner while waiting
            } else if (snapshot.hasError) {
              return Text("Error: ${snapshot.error}"); // Show error message if error occurred
            } else {
              return Text("Data: ${snapshot.data}"); // Display the data when loaded
            }
          },
        );
      }
    }