Home > database >  Accesing var defined in function to global flutter dart
Accesing var defined in function to global flutter dart

Time:02-03

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"),
        ),
      ),
    );
  }
}

CodePudding user response:

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"),
            ),
          ),
        );
      }
    }

CodePudding user response:

Need to declare essan from outside of the typicalFunction, when declaring inside the function, you can't use it outside the function that's why you need to declare it globally. And you need to initialize your function in init state.

int? essan;
void typicalFunction() {
    essan = 4;
  }

// call function in initState

@override
initState(){
  super.initState();
  typicalFunction();
}
  •  Tags:  
  • Related