首页 > 解决方案 > 如何在 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();
  }


}

标签: flutterdart

解决方案


您可以将其传递给它的构造函数:

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

推荐阅读