[SOLVED] Accesing var defined in function to global flutter dart

Issue

I want to :

get access and print value of variable called essan which is initialized inside my void typicalFunction(). Now i have announcement:

Undefined name ‘essan’. Try correcting the name to one that is defined, or defining the name.

import 'package:flutter/material.dart';

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

  @override
  State<MapSample> createState() => MapSampleState();
}

class MapSampleState extends State<MapSample> {
  void typicalFunction() {
    int essan = 4;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            print(essan); // P R O B L E M
          },
          child: const Text("press me"),
        ),
      ),
    );
  }
}

Solution

You must define a global value and call function because value is not initialized.

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

      @override
      State<MapSample> createState() => MapSampleState();
    }

    class MapSampleState extends State<MapSample> {
     int? essan;
     
     @override
  void initState() {
    super.initState();
   typicalFunction() // You may be call here
}
      void typicalFunction() {
        essan = 4;
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: ElevatedButton(
              onPressed: () {
               typicalFunction() // You may be call here
                print(essan ?? 0); // P R O B L E M
              },
              child: const Text("press me"),
            ),
          ),
        );
      }
    }

Answered By – Yasin Ege

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.