How can I use the result of an async function in a Text in Flutter?

Question

Asked by Gustavo B on November 05, 2021 (source).

I started learning Flutter this week. I'm trying to get the position of the device using the Geolocator package but I'm not used to async functions. I want to use the position.latitude inside the Text of AppBar title. I wrote < position information goes here > in the code to show the right place. Below is my code.

class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
  return Scaffold(
  appBar: buildAppBar(context),
);
}

AppBar buildAppBar(context) {
var position = null;

getCurrentPosition().then((position) => {position = position});

return AppBar(
    centerTitle: true,
    backgroundColor: kPrimaryColor,
    elevation: 0,
    toolbarHeight: MediaQuery.of(context).size.height * 0.07,
    title: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        IconButton(
          icon: const Icon(Icons.place),
          iconSize: 15,
          onPressed: () {},
        ),
        const Text(<position information goes here>,
            style: TextStyle(fontSize: 12)),
      ],
    ));
}

Future<Position> getCurrentPosition() async {
 Position position = await Geolocator.getCurrentPosition(
    desiredAccuracy: LocationAccuracy.high);

  return position;
  }
}

Answer

Question answered by ricarDEV (source).

  1. Your page must be stateful in order to change it state. Stateless widget are static, you can use them when your Widgets don't change and the user doesn't interact with the screen.
  2. You have to call the setState() method, so your page know's something has changed.
  3. Later, if you desire to evolve your code, use state management (MobX,GetX, Cubit, RxDart) instead of setStates. When you use setState, all the widgets under the widget-tree reload, so it consumes more CPU and GPU.

Try something like this:

import 'package:flutter/material.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  var position = null;

  @override
  void initState() {
    getCurrentPosition().then((position) {
      setState(() {
        position = position;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(context),
    );
  }

  AppBar buildAppBar(context) {
    return AppBar(
        centerTitle: true,
        backgroundColor: kPrimaryColor,
        elevation: 0,
        toolbarHeight: MediaQuery.of(context).size.height * 0.07,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              icon: const Icon(Icons.place),
              iconSize: 15,
              onPressed: () {},
            ),
            const Text(position ?? '', style: TextStyle(fontSize: 12)),
          ],
        ));
  }

  Future<Position> getCurrentPosition() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    return position;
  }
}

if you have some problem, give me a feedback.

ASYNC-AWAIT DART FLUTTER
SHARE: