如何从dart文件中获取上下文

问题描述 投票:0回答:1

我有此飞镖文件category_data.dart

import 'package:flutter/material.dart';

final List categories = [
  'Entertainment',
  'Sports',
  'Politics',
  'Science',
  'Technology',
  'Travel'
];
/*
  you can change your category here.
  If you change, make sure you have changed in the admin panel.
  Otherwise the app will show error.
*/

/*
  if your change the defalut category, make sure your category item munber is equal to category colors item number.
  Example: If you have 5 categories, then remove an color item in the category colors.
  else if you have more than 6 categories, then you have to add color items in the category colors List down below.
*/

final List categoryColors = [
  Colors.orange[200],
  Colors.blue[200],
  Colors.red[200],
  Colors.pink[200],
  Colors.purple[200],
  Colors.blueGrey[400]
];

我想通过国际插件添加国际化。为此,我正在使用以下代码来获取文本的语言环境翻译:

AppLocalizations.of(context).categoryName

然后,类别列表如下:

import 'package:flutter/material.dart';
import 'package:news_app/generated/l10n.dart';

final List categories = [
  AppLocalizations.of(context).entertainment,
  AppLocalizations.of(context).sports,
  AppLocalizations.of(context).politics,
  AppLocalizations.of(context).science,
  AppLocalizations.of(context).technology,
  AppLocalizations.of(context).travel
];

但是这段代码给我一个错误,因为我没有上下文:

Undefined name 'context'.
Try correcting the name to one that is defined, or defining the name

您如何获得使用国际化的环境?我只在小部件的build方法中看到了上下文。

flutter
1个回答
0
投票

我之前遇到过同样的问题,我解决的方法是创建一个GlobalKey

static GlobalKey rootWidgetKey = GlobalKey();

然后将其附加到您的根窗口小部件:

...
home: YourRootWidget(
  key: rootWidgetKey,
  ...

然后您可以通过参考root在任何地方访问rootWidgetKey.currentContext上下文。


0
投票

像示例一样在构建方法之后添加列表

 @override
 Widget build(BuildContext context) {
 final List categories = [
 AppLocalizations.of(context).entertainment,
 AppLocalizations.of(context).sports,
 AppLocalizations.of(context).politics,
 AppLocalizations.of(context).science,
 AppLocalizations.of(context).technology,
 AppLocalizations.of(context).travel
 ];
 return ...
© www.soinside.com 2019 - 2024. All rights reserved.