[英]Accesing var defined in function to global flutter dart
我想要:
獲取名為essan
的變量的訪問和打印值,該變量在我的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
,在typicalFunction
內部聲明時,不能在function 外部使用它,這就是為什么需要全局聲明它的原因。 您需要在 init state 中初始化您的 function。
int? essan;
void typicalFunction() {
essan = 4;
}
// call function in initState
@override
initState(){
super.initState();
typicalFunction();
}
您必須定義一個全局值並調用 function 因為值未初始化。
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 OBLEM }, child: const Text("press me"), ), ), ); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.