访问函数中定义的 var 到全局 flutter dart

Accesing var defined in function to global flutter dart

我要:

获取并打印名为 essan 的变量的值,该变量在我的 void typicalFunction() 中初始化。现在我有公告:

未定义的名称'essan'。尝试将名称更正为已定义的名称,或定义名称。

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

需要在typicalFunction外部声明essan,在函数内部声明时,您不能在函数外部使用它,这就是为什么需要全局声明它的原因。并且你需要在初始化状态下初始化你的函数。

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

// call function in initState

@override
initState(){
  super.initState();
  typicalFunction();
}

您必须定义一个全局值并调用函数,因为值未初始化。

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