无法在另一个 class 中获取变量 - Flutter

Can't get variable in another class - Flutter

告诉我,我需要在 block_info_page 中的 cubit 文件中获取一个 hash 变量。我需要这个变量来向使用 hash_block 变量的 block_repository 发出 API 请求。有可能实现吗?提前致谢。

class BlockinfoCubit extends Cubit<BlockInfoState> {
  final BlockInfoRepository _blockInfoRepository;

  BlockinfoCubit(this._blockInfoRepository) : super(BlockInfoInitialState());

  void getBlockInfo() async {
    emit(BlockInfoLoadingState());
    try {
      final hash_block = ; 
      final blocksInfo = await _blockInfoRepository.getBlockInfo(hash_block);
      emit(BlockInfoLoadedState(blocksInfo));
    } catch (e) {
      emit(BlockInfoErrorState(e.toString()));
    }
  }
}

block_info_page

class BlockInfoPage extends StatelessWidget {
  final String hash;
  const BlockInfoPage({Key? key, required this.hash}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Image.asset(
          'assets/images/logo.png',
          height: 35,
        ),
        centerTitle: false,
      ),
      body: Center(child: Text(hash)),
    );
  }
}

block_repository

class BlockInfoRepository {
  Future<List<BlockInfoModel>> getBlockInfo(hash_block) async {
    final response = await http
        .get(Uri.parse('https://blockchain.../$hash_block'));

    if (response.hashCode == 200) {
      final blockInfo = json.decode(response.body);

      return blockInfo
          .map<BlockInfoModel>((json) => BlockInfoModel.fromJson(json))
          .toList();
    } else {
      throw Exception('Failed to load block-info');
    }
  }
}

block_page

TextButton(
                              onPressed: () => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => BlockInfoPage(
                                          hash: blocksData[index].hash))),

这真的很简单。

先导入里面有变量的block_info_page

那么你有两种方法:

  1. 使哈希变量静态:static String hash;
  2. 对于另一种方式,您现在不需要做任何事情

方式 1

你可以这样获取变量: BlockInfoPage.hash;

它的作用是:从 class 中挑选变量,而无需再次构建整个 class


方式 2

你可以这样获取变量: BlockInfoPage().hash;

它所做的是:再次构建整个 class,然后从 class

中选择变量

如果这不起作用使变量成为全局变量 - 将散列变量放在 class

之外

您可以像这样访问全局变量:

  1. 先导入里面有全局变量的文件
  2. 您可以像访问包含全局变量的文件一样访问您的全局变量:hash

PS:因为你的全局变量不在class里面,它永远不会自动设置为起始值