我实现了一个从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中应该显示一个新的文本。
发布于 2019-07-03 09:52:53
你的方法和页面视图构建器在同一个有状态窗口小部件类中吗?更改" index“变量的名称,因为它可能会与pageview builder索引参数混淆,并声明一个默认值。
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(),
);
},
),https://stackoverflow.com/questions/56859826
复制相似问题