skip to Main Content

I am getting the referer for a header with a Future function and then I am trying to pass that to a build widget:

referer() async {
   refererFinal = await getReferer();
}

Map<String, String> loadHeaders() {
    Map<String, String> headers = new Map();
    headers['Referer'] = refererFinal!;
    return headers;
}


Image.network(URI,
   headers:loadHeaders(),
   errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
      return Image.asset(defaultImage);
   }
)

The problem is, referer() function loads after the build tree, so my headers remain blank.

How can I fix this?

UPDATE

This is my getReferer() method:

static Future<String?> getReferer() async {
   return headers!['referer'];
}

2

Answers


  1. You can wrap your image with FutureBuilder to build the widget once the referer() function completes.

    Future<String?> referer() async {
       return await getReferer();
    }
    
    FutureBuilder(
        future: referer(),
        builder: (BuildContext context, AsyncSnapshot<String?> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            var referer = snapshot.data!;
            return Image.network(
              URI,
              headers: {'Referer': referer},
              errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
                return Image.asset(defaultImage);
              },
            );
          } else {
            // Do something, maybe show a progress bar that it's loading
            // but you need to return a widget.
          }
        },
    );
    
    Login or Signup to reply.
  2. You can either check this manually with a bool variable and then display an empty container or similar if the headers have not been loaded yet.

    Or you can use the FutureBuilder widget created by Flutter, which was made especially for this purpose:

    https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

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