[英]Flutter FutureBuilder inside another FutureBuilder, Taken From JSON array of Strings
[英]FutureBuilder is able to get data but data is taken multiple times with Flutter
我正在使用一個簡單的 Json ,如下所示:
[
{
"question" : "Sky",
"answer" : "Blue",
},
{
"question" : "Sun",
"answer" : "Yellow",
},
]
並且能夠按照我的意願在文本小部件中獲取數據,問題是jsondecoder 多次獲取數據並創建多個屏幕,我知道這是因為我將 FutureBuilder 放在構建方法中,而當我將未來放在構建之外這個:
Future getDataArray() async {
final dynamic resp =
DefaultAssetBundle.of(context).loadString('load_json/words.json');
return resp;
}
@override
void initState() {
myFuture = getDataArray();
super.initState();
}
var mydata = JsonDecoder().convert(snapshot.data.toString());
仍在 build 和 FutureBuilder 中,這就是問題所在。 我無法獲得var mydata = JsonDecoder().convert(snapshot.data.toString());
在構建之外請幫助我。
構建方法是:
@override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.purple[900],
appBar: new AppBar(
title: Text(widget.title),
),
body: new Padding(
padding: EdgeInsets.fromLTRB(2, 20, 2, 20),
child: FutureBuilder(
future: myFuture,
builder: (context, snapshot) {
//decode json
var mydata = JsonDecoder().convert(snapshot.data.toString());
return new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
child: Card(
color: Colors.indigoAccent[400],
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.all(Radius.circular(24.0)),
),
elevation: 10.0,
shadowColor: Colors.black,
child: Stack(
fit: StackFit.loose,
alignment: Alignment.center,
children: <Widget>[
new Container(
width: 100.0,
height: 100.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24.0),
color: Colors.white,
),
child: Center(
child: Text(
mydata[index]['answer'],
style: TextStyle(
fontFamily: 'Arial',
fontSize: 20,
color: Colors.indigoAccent[400],
height: 1,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
),
),
],
),
),
onTap: () {
print('button1');
},
),
],
)
],
);
},
itemCount: mydata == null ? 0 : mydata.length,
);
},
)),
);
}
您好,親愛的,在您未來的建造者的水平上,您應該首先測試數據是否可用,然后才能完成 json 的轉換,我建議您:
FutureBuilder(
future: myFuture,
builder: (context, snapshot) {
if(snapshot.hasData){
var mydata = JsonDecoder().convert(snapshot.data.toString());
}else{
// no data available
}
);
社區,我使用了 ListView.builder,並且 itemCount 導致問題不是 json,我已經刪除了 ListView.builder,現在問題已解決。 如果有其他人像我一樣誤會他們的錯誤原因,這個問題可能會保留,但如果你認為這個問題並不常見,我可能會刪除它。 請在評論中這樣說。 謝謝你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.