Home > Back-end >  How can I use the result of an async function in a Text in Flutter?
How can I use the result of an async function in a Text in Flutter?

Time:11-05

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;
  }
}

CodePudding user response:

  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.

CodePudding user response:

I don't know exactly how do you want to use it. But I will give my solution as I understood the issue. First, change StatelessWidget to StatefulWidget.

Then you can define the position variable inside the HomeScreen class and set the current position to. Then send this variable as a parameter to the buildAppbar function:

AppBar buildAppBar(context, dynamic currentPos){...}

the variable currentPos is for storing the value got from async function named getCurrentPosition.

The Text widget accepts only String data type, so you can use currPos.toString() method or using it as you prefer.

To get the value of current position from the asynchronous function named getCurrentPosition and assigned it to the position variable when the widget being created and then send it to the buildAppbar function, you can do the following in your code.

*sorry see the code in the image. I wrote it in mobile because I don't have lap now and when I post the answer an error appears in code formatting. So I will tack a screenshot for code and add it here.

enter image description hereenter image description here

  • Related