簡體   English   中英

如何在 Flutter/dart 的另一個 class 中使用變量

[英]how to use a variable in another class in Flutter/dart

我有一個名為“位置”的 statfull class,它通過 Geolocatar 獲取位置,我用這個顯示位置:

 Text(currentPosition!=null? '$currentPosition' : '----',),

這是:

static Position? currentPosition;

我還有另一個名為“WeatherApi”的 class,我使用 Openweathermap Api 來獲取天氣。 現在我想在 api url 中使用currentPosition

https://api.openweathermap.org/data/2.5/weather?lat=44.34&lon=10.99&appid={API key}

如何使用 url 中的currentPosition 我試過 widget.variablename 但沒有用

您可以通過 WeatherApi class 的構造函數傳遞位置詳細信息。在 WeatherApi class 中創建最終變量(currentPosition)並根據需要進行設置,當您從位置屏幕導航到 WeatherApi 屏幕時,在

Navigator.push(context, //你的路線 => WeatherApi(currentPosition: currentPosition));

並使用變量,在 WeatherApi class中執行 widget.currentPosition

查看此以獲取更多信息

您可以在“位置”小部件外部定義一個全局變量作為“當前位置”,

 class Position { static String? currentPosition; }

從“位置”調用此變量並進行設置。

 class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override void initState() { Position.currentPosition = 'currentPosition'; super.initState(); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: TextButton( onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: ((context) => LocationWidget()), ), ); }, child: Text('Click Me'), ), ), ); } }

然后從“WeatherApi”再次調用它並使用它。

 class WeatherWidget extends StatefulWidget { const WeatherWidget({super.key}); @override State<WeatherWidget> createState() => _WeatherWidgetState(); } class _WeatherWidgetState extends State<WeatherWidget> { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text(Position.currentPosition?? 'null'), ), ); } }

在 Flutter 中,將變量從一個 class 傳遞到另一個的一種方法是使用構造函數:您可以在需要該變量的 class 的構造函數中將變量作為參數傳遞。 您可以閱讀官方文檔中的詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM