skip to Main Content

I have future builder working for the body of my app but not in the title. Please can you tell me how to use future builder in the title section, but still be able to access the same results array in the body section (without having to resend the database query in the body section)

This is the existing code with future builder working in the body section:

return Scaffold(
  appBar: AppBar(
    title: Text(data["name"]), // !!! need to be able to display data["name"] here

  ),
  body: FutureBuilder<DocumentSnapshot>(
    future: docRef.get(),
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Center(
          child: CircularProgressIndicator(),
        );
      } else if (snapshot.hasError) {
        return Center(
          // child: Text("Error: ${snapshot.error}"),
          child: Text("Oh no it's an error"),
        );
      } else {
        final data = snapshot.data!.data() as Map<String, dynamic>;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(data?["name"] ?? '' + " is my name"),
            Text(data?["shoe_size"] ?? '' + " is my shoe size"),

2

Answers


  1. One option would be to move the Scaffold one level up the tree. Meaning, wrap the entire page in a FutureBuilder and render a Scaffold once there’s data/error.

    Login or Signup to reply.
  2. For me the simplest answer would be to just create a variable which can be null. When the future builder has loaded the data, just assign the data to the variable with setState() and then in the app bar just do:

    return Scaffold(
      appBar: AppBar(
        title: Text(variableThatHoldsTheData ?? "Loading..."), 
      ),
      body:
    

    Another way is to load the data in initState and while your variable is null, just show a loading indicator on the page and then update it

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search