天天看點

dart - 如何在帶有DartFlutter的不同類上使用變量

我有一類是我的getToken類。在此類中,我得到的 token 是字元串 token 。這是我的 getToken.dart

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 類别

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

String _token;
String get token => _token    // To ensure readonly
​
Future<Null> setToken() async {
  // set your _token here
}           

複制

get_cari.dart

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.