Home > Back-end >  How to use a variable within a method elsewhere in Flutter?
How to use a variable within a method elsewhere in Flutter?

Time:11-21

I know this is a stupid question, but I'm asking as a newbie to flutter.

I created a getData() method to call Firebase's User data and display it on the app. And to call it, result.data() is saved as a variable name of resultData.

But as you know I can't use Text('user name: $resultData'). How do I solve this? It's a difficult problem for me, since I don't have any programming basics. thank you.

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:shipda/screens/login/login_screen.dart';
import 'package:get/get.dart';
import 'package:cloud_firestore/cloud_firestore.dart';


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

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

class _HomeScreenState extends State<HomeScreen> {
  final _authentication = FirebaseAuth.instance;
  User? loggedUser;
  final firestore = FirebaseFirestore.instance;

  void getData() async {
    var result = await firestore.collection('user').doc('vUj4U27JoAU6zgFDk6sSZiwadQ13').get();
    final resultData = result.data();
  }


  @override
  void initState() {
    super.initState();
    getCurrentUser();
    getData();
  }

  void getCurrentUser(){
    try {
      final user = _authentication.currentUser;
      if (user != null) {
        loggedUser = user;
        print(loggedUser!.email);
      }
    } catch (e){
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          children: [
            Text('Home Screen'),
            IconButton(
              onPressed: () {
                FirebaseAuth.instance.signOut();
                Get.to(()=>LoginScreen());
              },
              icon: Icon(Icons.exit_to_app),
            ),
            IconButton(
              onPressed: () {
                Get.to(() => LoginScreen());
              },
              icon: Icon(Icons.login),
            ),
            Text('UserInfo'),
            Text('user name:  ')

          ],
        ),
      ),
    );
  }
}

CodePudding user response:

By writing

  void getData() async {
    var result = await firestore.collection('user').doc('vUj4U27JoAU6zgFDk6sSZiwadQ13').get();
    final resultData = result.data();
  }

you make resultData only local to the function getData(). You should declare it outside. Also you need to put it in a setState to make it rebuild the screen after loading. I don't know what type it is, but if it's a String for example you could write

  String? resultData;

  void getData() async {
    var result = await firestore.collection('user').doc('vUj4U27JoAU6zgFDk6sSZiwadQ13').get();
    setState(() {
      resultData = result.data();
    });  
  }

Then you can use Text('user name: $resultData') for example

CodePudding user response:

What you are referring to is called state. It is a complex topic and you will have to start studying it to correctly develop any web based app.

Anyway, as for your situation, you should have resultData be one of the attributes of the _HomeScreenState class.

Then change resultData in a setState method, like this:

setState(() {
  resultData = result.data();
});

Then, in the Text widget, you can actually do something like:

Text("My data: "   resultData.ToString())

Instead of ToString of course, use anything you need to actually access the data.

  • Related