访问范围外的变量
Accessing variables out of scope
我正在尝试导航到一个新页面 newData[index]["title"]
当点击 listTile 时,我如何才能访问此范围之外的 newData、索引和数据变量,我知道我必须在全局范围内声明它们但是我尝试了 this.index,但它不起作用,我创建了一个 _onTap() 方法,但我无权访问索引,因此我只能通过询问特定位置 [0] 来访问。
class _ContentPageState extends State<ContentPage> {
@override
Widget build(BuildContext context,) {
List data;
return new Scaffold(
appBar: new AppBar(
title: new Text("Local json file"),
),
body: new Container(
child: new Center(
child: new FutureBuilder(
future: DefaultAssetBundle
.of(context)
.loadString('data_files/file.json'),
builder: (context, snapshot) {
var newData = JSON.decode(snapshot.data.toString());
return new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new Card(
child: new ListTile(
title: new Text(newData[index]['title'],textScaleFactor: 1.5),
),
);
},
itemCount: newData == null ? 0 : newData.length,
);
}),
),
));
}
}
我猜你正试图在你的 class 中使用一个类似于 :
的私有 _onTap
方法
_onTap(newData, int index) {
}
这很简单,在您的 ListTile
中,您可以将 _onTap
包装在另一个函数中,如下所示:
return new Card(
child: new ListTile(
onTap: () => _onTap(newData, index),
title: new Text(newData[index]['title'], textScaleFactor: 1.5),
),
);
之前的答案是将 newData 作为参数传递。另一种选择是在构建方法之外声明 newData。
class _ContentPageState extends State<ContentPage> {
var newData;// << here >> after class
@override
Widget build(BuildContext context,) {
所以,在assign remove de type (var)
newData = JSON.decode(snapshot.data.toString());
我正在尝试导航到一个新页面 newData[index]["title"]
当点击 listTile 时,我如何才能访问此范围之外的 newData、索引和数据变量,我知道我必须在全局范围内声明它们但是我尝试了 this.index,但它不起作用,我创建了一个 _onTap() 方法,但我无权访问索引,因此我只能通过询问特定位置 [0] 来访问。
class _ContentPageState extends State<ContentPage> {
@override
Widget build(BuildContext context,) {
List data;
return new Scaffold(
appBar: new AppBar(
title: new Text("Local json file"),
),
body: new Container(
child: new Center(
child: new FutureBuilder(
future: DefaultAssetBundle
.of(context)
.loadString('data_files/file.json'),
builder: (context, snapshot) {
var newData = JSON.decode(snapshot.data.toString());
return new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new Card(
child: new ListTile(
title: new Text(newData[index]['title'],textScaleFactor: 1.5),
),
);
},
itemCount: newData == null ? 0 : newData.length,
);
}),
),
));
}
}
我猜你正试图在你的 class 中使用一个类似于 :
的私有_onTap
方法
_onTap(newData, int index) {
}
这很简单,在您的 ListTile
中,您可以将 _onTap
包装在另一个函数中,如下所示:
return new Card(
child: new ListTile(
onTap: () => _onTap(newData, index),
title: new Text(newData[index]['title'], textScaleFactor: 1.5),
),
);
之前的答案是将 newData 作为参数传递。另一种选择是在构建方法之外声明 newData。
class _ContentPageState extends State<ContentPage> {
var newData;// << here >> after class
@override
Widget build(BuildContext context,) {
所以,在assign remove de type (var) newData = JSON.decode(snapshot.data.toString());