flutter - 如何在 Flutter 中使用 ChangeNotifier 将变量数据放入类中?
问题描述
我有以下类,它从远程 JSON 源中提取数据,如果我将 URL 硬编码到类(daUrl)中,那么它就很好用。
但是我打算使用一个变量 URL,当我调用它时我想将它输入到这个类中。但是在顶部声明变量是行不通的。
有任何想法吗?
class ThreadData with ChangeNotifier
{
Map<String,dynamic> _map = {};
bool _error = false;
String _errorMessage = '';
int _isLoggedIn = 0;
int tid = 1836392;
Map<String,dynamic> get map => _map;
bool get error => _error;
String get errorMessage => _errorMessage;
int get isLoggedIn => _isLoggedIn;
//var daUrl = 'https://jsonplaceholder.typicode.com/todos/';
Future<void> get fetchData async {
final response = await post(Uri.parse(daUrl));
if ((response.statusCode == 200) && (response.body.length >0))
{
try
{
debugPrint('\Thread => Make Call => Success\n');
_map = json.decode(response.body);
_error = false;
}
catch(e)
{
_error = true;
_errorMessage = e.toString();
_map = {};
_isLoggedIn = 0;
}
}
else
{
_error = true;
_errorMessage = 'Error: It could be your internet connection';
_map = {};
_isLoggedIn = 0;
}
notifyListeners(); // if good or bad we will notify the listeners either way
}
void initialValues()
{
_map = {};
_error = false;
_errorMessage = '';
_isLoggedIn = 0;
notifyListeners();
}
}
解决方案
您可以将其传递给它的构造函数:
class ThreadData with ChangeNotifier {
final String url;
// Defaults to some URL if not passed as parameter
ThreadData({this.url = 'https://jsonplaceholder.typicode.com/todos/'});
Map<String,dynamic> _map = {};
bool _error = false;
String _errorMessage = '';
int _isLoggedIn = 0;
int tid = 1836392;
Map<String,dynamic> get map => _map;
bool get error => _error;
String get errorMessage => _errorMessage;
int get isLoggedIn => _isLoggedIn;
Future<void> get fetchData async {
// Access the URL field here
final response = await post(Uri.parse(this.url));
if ((response.statusCode == 200) && (response.body.length >0))
{
try
{
debugPrint('\Thread => Make Call => Success\n');
_map = json.decode(response.body);
_error = false;
}
catch(e)
{
_error = true;
_errorMessage = e.toString();
_map = {};
_isLoggedIn = 0;
}
}
else
{
_error = true;
_errorMessage = 'Error: It could be your internet connection';
_map = {};
_isLoggedIn = 0;
}
notifyListeners(); // if good or bad we will notify the listeners either way
}
void initialValues()
{
_map = {};
_error = false;
_errorMessage = '';
_isLoggedIn = 0;
notifyListeners();
}
}
然后你可以这样称呼它:
ThreadData(); // the URL will be https://jsonplaceholder.typicode.com/todos/
ThreadData(url: 'https://example.com'); // the URL will be https://example.com
推荐阅读
- pandas - 使用 plotly 按列名着色
- javascript - React 组件更新较晚
- android - 如何请求 GPS 定位许可以“始终允许”?
- amazon-s3 - Quicksight Athena - [Simba][AthenaJDBC](100071) AWS Athena 客户端引发错误
- c - 数组中的随机字符不重复
- javascript - Swiper 更改延迟加载的图像
- python-3.x - 如何使用 AWS python3 Lambda 将数据发送到 S3 存储桶?
- mysql - 如何旋转此源表
- python - Pandas:ValueError:工作表索引 0 无效,找到 0 个工作表
- java - 为什么屏幕尺寸看起来比实际尺寸大 android studio