17. Flutter Tutorial for Beginners – Flutter FutureBuilder

0
767

Let’s say you want to fetch data from backend on launch of page and show loader till data comes. In future builder, it calls the future function to wait for the result, and as soon as it produces the result it calls the builder function where we build the widget.

I need to make sure my little loading spinner is displaying right and then goes away, somewhere, there’s a delayed future helping me out.

Future getUserOrder(int orderId) {
  if (orderId == 4045)
    return Future.delayed(Duration(seconds: 3), () => 'Latte Macchiato');
  else
    return Future.delayed(Duration(seconds: 3),
            () => throw Exception('Failed: Order id is invalid'));
}

Here we use FutureBuilder. You give it a Future and builder method, and it will automatically rebuild its children when the Future completes.

Center(
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      FutureBuilder(
          future: getUserOrder(4045),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text(snapshot.data,style: Theme.of(context).textTheme.headline);
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}",style: Theme.of(context).textTheme.headline);
            } else {
              return CircularProgressIndicator();
            }
          }),
    ],
  ),
)

Full Example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FutureBuilder(
                future: getUserOrder(4045),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return Text(snapshot.data,style: Theme.of(context).textTheme.headline);
                  } else if (snapshot.hasError) {
                    return Text("${snapshot.error}",style: Theme.of(context).textTheme.headline);
                  } else {
                    return CircularProgressIndicator();
                  }
                }),
          ],
        ),
      ),
    );
  }
}

Future getUserOrder(int orderId) {
  if (orderId == 4045)
    return Future.delayed(Duration(seconds: 3), () => 'Latte Macchiato');
  else
    return Future.delayed(Duration(seconds: 3),
            () => throw Exception('Failed: Order id is invalid'));
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here