Flutter中如何跨文件访问获取API Key的getKey()函数
跨文件共享API密钥的几种实用方案
1. 抽成独立工具类(最推荐)
把获取密钥的逻辑单独拎出来,放在一个通用工具文件里,比如api_utils.dart,这样两个页面都能轻松调用:
// api_utils.dart import 'package:http/http.dart' as http; import 'dart:convert'; class ApiUtils { // 封装获取密钥的方法 static Future<String> getKey() async { final response = await http.get(Uri.parse('你的密钥接口地址')); if (response.statusCode == 200) { // 这里根据接口返回结构调整,取出dataKey return jsonDecode(response.body)['dataKey']; } else { throw Exception('获取API密钥失败'); } } }
之后在todolist.dart和add_new_item.dart里直接导入调用:
import 'api_utils.dart'; // 在需要的异步方法里调用 String apiKey = await ApiUtils.getKey();
2. 加缓存避免重复请求
如果不想每次切换页面都发请求拿密钥,可以在工具类里加个静态变量缓存已获取的密钥:
// api_utils.dart class ApiUtils { static String? _cachedKey; // 缓存密钥 static Future<String> getKey() async { // 有缓存直接返回,不用再请求 if (_cachedKey != null) { return _cachedKey!; } final response = await http.get(Uri.parse('你的密钥接口地址')); if (response.statusCode == 200) { _cachedKey = jsonDecode(response.body)['dataKey']; return _cachedKey!; } else { throw Exception('获取API密钥失败'); } } }
3. 用状态管理全局共享(适合复杂项目)
如果你的项目已经在用Provider、Bloc这类状态管理库,可以把密钥存在全局状态里,方便所有页面访问:
第一步:创建Provider类
// api_key_provider.dart import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; class ApiKeyProvider extends ChangeNotifier { String? _apiKey; String? get apiKey => _apiKey; Future<void> fetchApiKey() async { final response = await http.get(Uri.parse('你的密钥接口地址')); if (response.statusCode == 200) { _apiKey = jsonDecode(response.body)['dataKey']; notifyListeners(); // 通知页面更新 } else { throw Exception('获取API密钥失败'); } } }
第二步:在main.dart注册Provider
import 'package:flutter/material.dart'; import 'api_key_provider.dart'; void main() { runApp( ChangeNotifierProvider( create: (_) => ApiKeyProvider(), child: const MyApp(), ), ); }
第三步:在页面中获取密钥
// 不管是todolist.dart还是add_new_item.dart import 'package:flutter/material.dart'; import 'api_key_provider.dart'; // 在State类里调用 final apiKeyProvider = Provider.of<ApiKeyProvider>(context, listen: false); // 先检查有没有密钥,没有就请求 if (apiKeyProvider.apiKey == null) { await apiKeyProvider.fetchApiKey(); } String? apiKey = apiKeyProvider.apiKey;
4. 直接导入原文件(临时应急用,不推荐)
如果只是临时测试,可以直接在add_new_item.dart里导入todolist.dart,但这种方式会让代码耦合度变高,后期不好维护:
// add_new_item.dart import 'todolist.dart'; // 假设getKey()是todolist.dart里的全局函数 String apiKey = await getKey(); // 如果getKey()是某个类的静态方法,就这么调: // String apiKey = await TodoListPage.getKey();
内容的提问来源于stack exchange,提问作者Ninna Svanström
相关产品推荐
相关产品推荐

