Flutter-尝试解析本地json数据时出现“范围错误(长度)”

时间:2019-12-03 10:32:54

标签: json flutter dart

我有一个包含文本的JSON文件,每个句子都在一个单独的JSON对象中,用户应该能够使用next()previous()在哨点之间导航,但是当应用加载时,我得到了此错误:

  

RangeError(索引):无效值:有效值范围为空:0

直到我按下并加载文本并显示出来的屏幕上的任何其他按钮。

卡本身是一个有状态的小部件,这是我的代码:

class _BottomCardsState extends State<BottomCards>{

  bool isLoadingEnded = false;

  Future<Null> getAllData() async{
    await DefaultAssetBundle.of(context).loadString('assets/json/data.json').then((response){
      isLoadingEnded = true;
      var decodedData = json.decode(response);
        for(Map d in decodedData){
          dataList.add(Data.fromJson(d));
        }      
    });
  }

  @override
  void initState() {
    super.initState();
    getAllData();
  }

  int dataIndex = 0;

  @override
  Widget build(BuildContext context) {
    int myNbr = dataList[dataIndex].id;
    return Container(
      child: Material(
        color: Colors.transparent,
        child: Card(
          margin: EdgeInsets.symmetric(horizontal: 10.0),
          elevation: 6.0,
          child: Container(
            alignment: Alignment.topCenter,
            padding: EdgeInsets.symmetric(horizontal: 12.0,),
            child: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    IconButton(                  
                      splashColor: gradientStart,
                      icon: Icon(Icons.keyboard_arrow_left,),
                      onPressed: () {_previous();},
                    ),
                    IconButton(
                      splashColor: gradientStart,
                      icon: Icon(Icons.keyboard_arrow_right,),
                      onPressed: () {_next();},
                    ),
                  ],
                ),
                SizedBox(height: 4.0,),
                isLoadingEnded == true ? Container(
                  child: Column(
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        mainAxisSize: MainAxisSize.max,
                        children: <Widget>[
                          Expanded(                  
                            child: InkWell(
                              splashColor: Colors.lightBlue[100],
                              onTap: (){},
                              //the paragraph gets displayed here
                              child: Text(dataList[dataIndex].paragraph,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 8.0,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        mainAxisSize: MainAxisSize.max,
                        children: <Widget>[
                          Chip(
                            backgroundColor: secondaryDark,
                            label: Text('Number: $myNbr',
                            style: TextStyle(color: Colors.white, fontSize: 10.0, fontWeight: FontWeight.w500),),
                          ),
                        ],
                      ),
                    ],
                  ),
                ): Center(child: loadingIndicator(),),
                SizedBox(height: 6.0),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

` 我的JSON格式:

{
    "id": 1,
    "paragraph": "lorem ipsum"
},
...

2 个答案:

答案 0 :(得分:1)

您需要等待数据填满。

更改您的getAllData方法。喜欢,

equals()

现在等待构建方法。喜欢,

Future<List<Data>> getAllData() async{
    var response = await DefaultAssetBundle.of(context).loadString('assets/json/data.json')
    var decodedData = json.decode(response);
    for(Map d in decodedData){
        dataList.add(Data.fromJson(d));
    }  
    return dataList;
}

答案 1 :(得分:0)

import'package:flutter / services.dart'显示rootBundle;

秋天,您的数据就像一张地图,并且您试图将其存储在列表中。如我所见,您的数据就是地图的类型。

{
    "id": 1,
    "paragraph": "lorem ipsum"
}

Future<void> getAllData() async {
 final res= await rootBundle.loadString('assets/config.json');
 final json = jsonDecode(res.body);
 var parse = json as Map; 
 Data data=Data.fromJson(parse);
}

如果JSON包含列表数据,则

[
{
    "id": 1,
    "paragraph": "lorem ipsum"
},
{
    "id": 1,
    "paragraph": "lorem ipsum"
}
]

然后

 Future<void> getAllData() async {
      final res= await rootBundle.loadString('assets/config.json');
     final json = jsonDecode(res.body);
     var parse = json as List;
     parse.forEach((d){ 
     dataList.add(Data.fromJson(d));
     });
    }