Making Future Calls In Flutter Futurebuilder Widget

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

When the asynchronous operation starts running then it returns a Future to the calling function. It says, “I’m going to have to wait on some stuff. Here’s this empty box, you hold onto that, and when I’m done, I’ll call the return statement and put some data in there for you”. You can put it in a FutureBuilder or something.

Making Future Calls In Flutter Future builder Widget

Making Future Calls In Flutter Futurebuilder
Complete Code For Making Future Calls In Flutter Futurebuilder In Flutter
main.dart

import 'package:flutter/material.dart';
import 'dart:async';

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Sample Divider Widget',
      home: HomePageState(),
    );
  }
}

class HomePageState extends StatefulWidget {
  HomePageState({Key key}) : super(key: key);

  @override
  _FutureBuilderWidgetState createState() => _FutureBuilderWidgetState();
}

Future getDataFromFuture()
async {
  return new Future.delayed(const Duration(seconds: 1), ()=>"Wait is over!");
}

class _FutureBuilderWidgetState extends State {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("Sample FutureBuilder Widget"),
          backgroundColor: Colors.blue[900],
        ),
        body: Center(
          child:Column(
            children: [
              Container(child: Image.network(
                  "https://franklinchristianchurch.com/wp-content/uploads/2017/11/Waiting_web.jpg"),),
              SizedBox(height: 30,),
              FutureBuilder(
                  future: getDataFromFuture(),
                  builder: (context, snapshot){
                    if(snapshot.data != null)
                    {
                      return Center(
                        child: Text(snapshot.data,
                          style: TextStyle(
                              color: Colors.blue[900],
                              fontSize: 40.0,
                              fontWeight: FontWeight.bold
                          ),),);
                    }
                    return CircularProgressIndicator();
                  })
            ],
          ),
        )
    );
  }
}

Related Post