Run asynchronous code before building your widget

Overview

Loader

Sometimes you need to load some data before building your widget. Because initState doesn't support asynchronous loading you need to find another way to load your data. The most common way of loading data is using a FutureBuilder but FutureBuilders are tedious. Another way is using flags to rebuild the widget after all the loading is done.

Loader uses the flag method.

LoadingMixin

The LoadingMixin adds all the necessary flags to your stateful widget's state to turn it to a FutureBuilder like widget.

load is called before the first didChangeDependencies, so you can use context to access inherited widgets.

their are two flags:

  1. loading : true if the load function is still running
  2. hasError: true if the load function has thrown an exception.

the exception text is stored in the error variable.

class HomePage extends StatefulWidget {

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


class _HomePageState extends State<HomePage> with LoadingMixin<HomePage> {

  Data _data;

  @override
  Future<void> load() async {
    var loader = FileLoader();
    _data = await loader.loadData();
  }

  @override
  Widget build(BuildContext context) {
    Widget body;
    if (loading) {
      body = Container();
    } else if (hasError) {
      body = Text(error);
    } else {
      body = DataViewer(_data);
    }
    
    return Scaffold(
      appbar: AppBar(),
      body: body,
    );
  }
}

StatelessLoadingMixin

For this mixin to work, you need to delete the build method and use the futureBuild method instead.

class FutureText extends StatelessWidget with StatelessLoadingMixin {
  final Future<String> futureText;
  final TextStyle style;

  FutureText(this.futureText, {this.style});

  String text;

  @override
  Future<void> load() async {
    text = await futureText;
  }

  @override
  Widget futureBuild(BuildContext context) {
    return Text(
      text,
      style: style,
    );
  }
}

Loader

Loader is a widget which uses the LoadingMixin mixin.

This widget will run it's builder method, only after the load function is done.

The builder will get the value returned in the load function as the value parameter.

class Banner extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Loader<String>(
          load: () async{
            return await retriveBannerText();
          },
          builder: (context, value){
            return Text(value);
          },
          errorBuilder: (error) => Text(error, style: TextStyle(color: Colors.red),),
        ),
      ),
    );
  }
}

Implementations details

StatelessLoadingMixin is implemented using the Loader widget.

The Loader widget is implemented using LoadingMixin.

LoadingMixin is implemented using flags on a stateful widget.

You might also like...

Experiment for building file system.

experiment_file_system A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you s

Nov 15, 2021

A Dice App for flutter beginners when building with State

dicee A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is

Nov 15, 2021

Dart HTTP server framework for building REST APIs. Includes PostgreSQL ORM and OAuth2 provider.

Dart HTTP server framework for building REST APIs. Includes PostgreSQL ORM and OAuth2 provider.

Aqueduct is a modern Dart HTTP server framework. The framework is composed of libraries for handling and routing HTTP requests, object-relational mapp

Jan 5, 2023

We are building an open database of COVID-19 cases with chest X-ray or CT images.

We are building an open database of COVID-19 cases with chest X-ray or CT images.

🛑 Note: please do not claim diagnostic performance of a model without a clinical study! This is not a kaggle competition dataset. Please read this pa

Jan 7, 2023

A declarative library with an easy-to-use interface for building Flutter applications on AWS.

A declarative library with an easy-to-use interface for building Flutter applications on AWS.

Amplify Flutter AWS Amplify provides a declarative and easy-to-use interface across different categories of cloud operations. Our default implementati

Jan 5, 2023

Bosun is a library for building organized command line applications in Dart.

Bosun A library for parsing CLI input and structuring CLI commands Features Structure CLI commands in a nice, uniform fashion. Parse args and flag inf

Oct 13, 2022

Ready for Building Production-Ready Healthcare/ Doctor Consult Android and iOS app UI using Flutter.

Ready for Building Production-Ready Healthcare/ Doctor Consult Android and iOS app UI using Flutter.

Production-Ready Doctor Consultant App - Flutter UI Packages we are using: flutter_svg: link In this full series, we will show you how to Building Pro

Nov 28, 2022

An application of learning outcomes from the Mastering Flutter 2.0 class: Building Travel and Aircraft Applications Buildwithangga

An application of learning outcomes from the Mastering Flutter 2.0 class: Building Travel and Aircraft Applications Buildwithangga

An application of learning outcomes from the Mastering Flutter 2.0 class: Building Travel and Aircraft Applications Buildwithangga

Aug 29, 2022

Flutter SDK for building a realtime broadcaster using the Millicast platform

Flutter SDK for building a realtime broadcaster using the Millicast platform. This Software Development Kit (SDK) for Flutter allows developers to simplify Millicast services integration into their own Android and iOS apps.

Oct 29, 2022
Comments
  • does not work

    does not work

    Loader<String>( load: () async { return "Hello World"; }, builder: (context, value) { return Text(value); }, )

    results into

    I/flutter (13848): The following assertion was thrown building Loader<String>(dirty, state: _LoaderState#2fafb): I/flutter (13848): type '(BuildContext, String) => Text' is not a subtype of type '(BuildContext, dynamic) => Widget'

    opened by filly82 1
Owner
Ali Ghanbari
Software engineering student at Persian Gulf University
Ali Ghanbari
A discord bot, made with Dart, which lets you run your own pure Dart code snippets directly via a discord ping, and get the output in an instant.

A discord bot, made with Dart, which lets you run your own pure Dart code snippets directly via a discord ping, and get the output in an instant.

Anikate De 3 Oct 21, 2022
Hybrid App build on flutter SDK able to run on Android, IOS, web, desktop

Codeforces Visualizer APP Ready to use Flutter Application. Uses codeforces API. Useful for codeforces programmers. ScreenShots Single User Page Compa

vikas yadav 13 Dec 31, 2022
Flutter example project to run Solidity smart contracts using web3Dart library

Fluthereum Description Flutter example project to run Solidity smart contracts using web3Dart library Dependencies web3dart: A dart library that conne

Marcos Carlomagno 72 Dec 27, 2022
how to set up for run the application on desktop

e_learning_app A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started i

FlutterDevs 11 Nov 1, 2022
Flutter plugin to run all creme sharing routines.

Creme Share plugin A Flutter plugin to share content from your Flutter app to social apps. Platform Support Android (WIP) iOS ❌ ✔️ Usage To use this p

Creme 10 Dec 20, 2022
Front-end of multiplayer web3 games implemented with Flutter to run on all platforms (Web, Android, iOS, Linux, Window, macOS, TV-OS)

Front-end of multiplayer web3 games implemented with Flutter to run on all platforms (Web, Android, iOS, Linux, Window, macOS, TV-OS)

R-Team 5 Nov 15, 2022
A guideline for building scalable Flutter applications.

Scalable flutter app You probably need to read this article before inspecting the repo's code. Building scalable Flutter apps (Architecture, Styling,

Nour El-Din Shobier 36 Nov 23, 2022
A Flutter package for building custom skeleton widgets to mimic the page's layout while loading.

Skeletons A Flutter package for building custom skeleton widgets to mimic the page's layout while loading. Examples Items ListView (Default) ListView

Moh Badjah 46 Dec 17, 2022
building a timer application using the bloc library

flutter_timer A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if

Simon Wambua 0 Nov 4, 2021
Building a Chat App with Firebase, Image Upload, Push Notifications

chat_app A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this

Trần Văn Nguyên 2 Nov 15, 2021