我已经实现了一个页面视图,该页面视图解析JSON中的数据。 我想如何通过点击功能实现随机播放按钮,以动态更改页面中的数据。
我尝试创建带有增量选项的函数,并在按钮的onPressed中传递了它。在调试控制台中,它显示编号已更新,但是在页面视图中,数据没有更改。
var index;
void _random() {
setState(() {
index = Random(index).nextInt(3000);
});
}
child: new FutureBuilder(
future: DefaultAssetBundle.of(context)
.loadString('json/quotes.json'),
builder: (context, snapshot) {
var quote = json.decode(snapshot.data.toString());
return new PageView.builder(
itemBuilder: (BuildContext context, int index) {
return new PageView(
children: <Widget>[
new Container(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Padding(
padding: const EdgeInsets.only(left: 19),
child: Text(
"" + quote[index]['Quote'],
style: TextStyle(
fontSize: 30,
color: Colors.white,
fontFamily: "fontaa",
fontWeight: FontWeight.bold,
letterSpacing: 2.25,
),
),
),
),
),
],
);
},
physics: BouncingScrollPhysics(),
);
},
),
child: new RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
elevation: 10,
color: Colors.black,
child: new Icon(
Icons.panorama_fish_eye,
color: Colors.white,
),
onPressed: () {
_random();
print("$index");
},
splashColor: Colors.yellow.shade400,
),
我需要一个结果,当我点击按钮时,应在pageView中显示一个新文本。
答案 0 :(得分:1)
您的方法和综合浏览量构建器是否在同一个有状态小部件类中?更改您的“索引”变量的名称,因为它可能会与您的综合浏览量索引参数混淆,并声明一个默认值。
var _index;
@override
initState(){
//initialize the index to random value
_random();
}
void _random() {
setState(() {
//not advisable to start the range with index
//as the range might get smaller if index is near to 3000
_index = Random(_index).nextInt(3000);
});
}
child: new FutureBuilder(
future: DefaultAssetBundle.of(context)
.loadString('json/quotes.json'),
builder: (context, snapshot) {
var quote = json.decode(snapshot.data.toString());
return new PageView.builder(
itemBuilder: (BuildContext context, int index) {
return new PageView(
children: <Widget>[
new Container(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Padding(
padding: const EdgeInsets.only(left: 19),
child: Text(
"" + quote[_index]['Quote'],
style: TextStyle(
fontSize: 30,
color: Colors.white,
fontFamily: "fontaa",
fontWeight: FontWeight.bold,
letterSpacing: 2.25,
),
),
),
),
),
],
);
},
physics: BouncingScrollPhysics(),
);
},
),