dart - 如何在带有DartFlutter的不同类上使用变量

2021-08-03 14:30:03 浏览数 (1)

我有一类是我的getToken类。在此类中,我得到的 token 是字符串 token 。这是我的 getToken.dart

代码语言:javascript复制
class GetToken {
  String token;
  Future<Null> getData() async {
    var url = "http://192.168.1.39:7070/api/v2/token";
    http.post(url, body: {
      "grant_type": "string",
      "branchcode": "string",
      "password": "string",
      "username": "string",
      "dbname": "string",
      "dbuser": "string",
      "dbpassword": "string",
      "dbtype": "string"
    }).then((response) {
      print("Response Status: ${response.statusCode}");
      //print("Response Body: ${response.body}");
      print('access token is -> ${json.decode(response.body)['access_token']}');
      token = json.decode(response.body)['access_token'];
    });
  }
}

我想在我的getCari类中使用此 token ,并在我的rest api中获取Json值。这是我的 getCari.dart 类别

代码语言:javascript复制
class GetCari{
  getCari() async {
    final response = await http.get("http://192.168.1.39:7070/api/v2/ARPs",
    headers: {HttpHeaders.AUTHORIZATION: token});
​
    if(response.statusCode ==200){
      return Cari.fromJson(json.decode(response.body));
    }else{
      throw Exception("Failed to Load");
    }
  }
}

我想问一下如何在我的getCari.dart类中使用我的 token (从getToken.dart获取)。我如何将 token 变量传递给其他类?

最佳答案

请使用Dart的顶级函数而不是不需要实例化的类。

这在Effective Dart documentation中提到

token_manager.dart

代码语言:javascript复制
String _token;
String get token => _token    // To ensure readonly
​
Future<Null> setToken() async {
  // set your _token here
}

get_cari.dart

代码语言:javascript复制
import 'token_manager.dart' as token_manager    // use your import path here
​
getCari() async {
  // You can now access token from token_manager from any class like this.
  final String token = token_manager.token;
}

摘抄

In Java and C#, every definition must be inside a class, so it’s common to see “classes” that exist only as a place to stuff static members. Other classes are used as namespaces—a way to give a shared prefix to a bunch of members to relate them to each other or avoid a name collision. Dart has top-level functions, variables, and constants, so you don’t need a class just to define something. If what you want is a namespace, a library is a better fit. Libraries support import prefixes and show/hide combinators. Those are powerful tools that let the consumer of your code handle name collisions in the way that works best for them. If a function or variable isn’t logically tied to a class, put it at the top level. If you’re worried about name collisions, give it a more precise name or move it to a separate library that can be imported with a prefix.

0 人点赞