Home > front end >  Flutter > How to load an image using FutureBuilder
Flutter > How to load an image using FutureBuilder

Time:08-19

How can i get the image of an url and display it using FutureBuilder.

FutureBuilder(
               future: httpClient.get(url),
               builder: (context, snapshot) {
                 if (snapshot.hasData) {
                    return CircleAvatar(
                       backgroundImage: snapshot.data,
                       radius: 30.0,
                    );
                 } else {
                    return const CircularProgressIndicator();
                  }
                }),

I'm using an httpClient for intercept requests and hang a header with a Token on. I have no idea how to get the image from this url to the backgroundImage of the CircleAvatar. Any help?

CodePudding user response:

Instead of using a FutureBuilder to make an http request of an image, why don't you use an NetworkImage widget: https://docs.flutter.dev/cookbook/images/network-image

CircleAvatar(
    backgroundImage: NetworkImage(
    'https://www.example.com/media/test.png',
    headers: {"Authorization": "Bearer $apiToken",),
    radius: 30.0,
)

UPDATE

To get the token from localStorage, assuming you use SharedPreference, do like this:

...
class _MyWidgetState extends State<MyWidget> {
  String _jwt = '';

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

  _getTokenFromStorage() async {
    var prefs = await SharedPreferences.getInstance();

    setState(() {
      _jwt = prefs.getString("token") ?? '';
    });
  }
...

And then you can pass the _jwt to the headers parameter

  • Related