FutureBuilder in Flutter

326

FutureBuilder widget is used to create widgets based on the latest snapshot of interaction with a Future. It is a widget that will help you to execute some asynchronous function and based on that function’s result your UI will update.

In this tutorial, we will discuss about futurebuilder in flutter. Here, we will discuss each and every aspects of FutureBuilder in flutter.

Constructors of FlutterBuilder

(new) FutureBuilder<String> FutureBuilder({
  Key? key,
  Future<String>? future,
  String? initialData,
  required Widget Function(BuildContext, AsyncSnapshot<String>) builder,
})

When we use the FutureBuilder widget we need to check for future state i.e future is resolved or not and so on. There is various State as follows:

ConnectionState.none: It means that the future is null and initialData is used as defaultValue.

ConnectionState.active: It means the future is not null but it is not resolved yet.

ConnectionState.waiting: It means the future is being resolved, and we will get the result soon enough.

ConnectionState.done: It means that the future has been resolved.

Code Implementation

splash_screen.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutterhopeprojects/Views/future_builder.dart';

class Splash extends StatefulWidget {
  const Splash({Key? key}) : super(key: key);

  @override
  State<Splash> createState() => _SplashState();
}

class _SplashState extends State<Splash> {
  @override
  void initState() {
    super.initState();
    Timer(const Duration(seconds: 3), () {
      Navigator.pushReplacement(context,
          MaterialPageRoute(builder: (_) => const FutureBuilderExample()));
    });
  }

  @override
  Widget build(BuildContext context) {
    // ignore: prefer_const_constructors
    return Scaffold(
      body: const Center(
        child: SizedBox(
          height: 150,
          width: 150,
          child: FlutterLogo(
            size: 20.0,
          ),
        ),
      ),
    );
  }
}

future_builder.dart

import 'package:flutter/material.dart';

Future<String> getValue() async {
  await Future.delayed(const Duration(seconds: 3));
  return 'Flutter Hope';
}

class FutureBuilderExample extends StatefulWidget {
  const FutureBuilderExample({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _FutureBuilderExampleState();
  }
}

class _FutureBuilderExampleState extends State<FutureBuilderExample> {
  late Future<String> _value;

  @override
  initState() {
    super.initState();
    _value = getValue();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: const Text('Flutter FutureBuilder Demo'),
      ),
      body: SizedBox(
        width: double.infinity,
        child: Center(
          child: FutureBuilder<String>(
            future: _value,
            initialData: 'Future Builder Demo',
            builder: (
              BuildContext context,
              AsyncSnapshot<String> snapshot,
            ) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const CircularProgressIndicator(),
                    Visibility(
                      visible: snapshot.hasData,
                      child: Text(
                        "${snapshot.data}",
                        style:
                            const TextStyle(color: Colors.black, fontSize: 24),
                      ),
                    )
                  ],
                );
              } else if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  return const Text('Error');
                } else if (snapshot.hasData) {
                  return Text("${snapshot.data}",
                      style: const TextStyle(color: Colors.cyan, fontSize: 36));
                } else {
                  return const Text('Empty data');
                }
              } else {
                return Text('State: ${snapshot.connectionState}');
              }
            },
          ),
        ),
      ),
    );
  }
}

Output:

Here is the github link of this project:

https://github.com/NilamPathak578/flutterHopeProjects/tree/futureBuilder

Thank you for reading this article. If you have any queries regarding any topic, feel free to share with us. We will try to solve your problems.

Happy Learning.

Leave A Reply

Your email address will not be published.