Skip to content

Passing a completed future in FutureBuilder does not produce initial snapshot with data #22687

@Steelsmasher

Description

@Steelsmasher

When I pass an already completed future into a FutureBuilder, the initial data isn't reflected in the snapshot until the next build cycle.

The code below waits for a future to complete before passing it to a FutureBuilder. I would expect the snapshot to have data on the first instance of the widget yet it doesn't?

main.dart

import 'package:flutter/material.dart';

main() {
    runApp(
        MaterialApp(
            home: Scaffold(
                body: Page(),
            ),
        ),
    );
}

class Page extends StatefulWidget {
    createState() => PageState();
}

class PageState extends State<Page> {

    Future<int> myFuture;
    String myText;

    initState(){
        super.initState();
        myFuture = Future.delayed(Duration(seconds: 5)).then((_){
            setState(() => myText = "I want this to display");
            return 0;
        });
    }

    build(context){
        if(myText == null){
            return Center(
                child: Text('Waiting for future to complete')
            );
        } else {
            return FutureBuilder(
                future: myFuture,
                builder: (context, snapshot) {
                    if(!snapshot.hasData) myText = "I don't want this to display";
                    return Center(
                        child: Text(myText)
                    );						
                }
            );
        }
    }
}

I'm aware of the 'initialData' parameter, but my use case means the the only data I can use only resides in the completed Future.

For now I'm using a workaround made of Stateful widgets but I would'nt think this was intended functionality of FutureBuilder?

Flutter Doctor

[√] Flutter (Channel master, v0.9.3-pre.17, on Microsoft Windows [Version 10.0.17134.285], locale en-GB)
[√] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[X] Android Studio (not installed)
[√] VS Code (version 1.27.2)
[√] Connected devices (1 available)

! Doctor found issues in 1 category.

Metadata

Metadata

Assignees

No one assigned

    Labels

    frameworkflutter/packages/flutter repository. See also f: labels.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions