我从JSON文件中获取数据时遇到范围错误

时间:2019-09-06 12:08:59

标签: flutter dart

我制作了一个从json文件中获取数据的函数,并且当我的fetch函数运行时,我将数据显示到一页上,直到该数据获取后3到4秒,直到Json提取为止,它都会显示erorr并成功显示但是屏幕上显示的错误非常尴尬。

import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(News1());

class News1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(

      title: "Flutter",
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List data = [];

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

  void fetchData() async {
    final response = await http.get('jsonfilelinkhere');

    if (response.statusCode == 200) {
      setState(() {
        data = json.decode(response.body);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    return Scaffold(

      body: Padding(
          padding: EdgeInsets.only(left: 50 ,right: 50),
        child:ListView(
          children: <Widget>[
            Center(
              child: Text(data[3]['Head']),
            ),
            Center(
              child: Text(data[0]['Description']),
            ),
            Image.network(data[0]['ImgUrl']),

          ],
        ),
      )
    );
  }
}

3 个答案:

答案 0 :(得分:1)

希望您能得到答案。如果您可以检查数组是否为null,请显示CircularProgressIndicator(),,否则显示数据。如果您无法执行此操作,我可以为您共享代码。

答案 1 :(得分:0)

在实际加载数据之前显示该数据时遇到了错误。

使用FutureBuilder解决您的问题。

示例代码:

import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(News1());

class News1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(

      title: "Flutter",
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List data = [];

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

  Future<Map<String, dynamic>> fetchData() async {
    final response = await http.get('jsonfilelinkhere');

    if (response.statusCode == 200) {
      setState(() {
        return json.decode(response.body);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    return Scaffold(

      body: Padding(
          padding: EdgeInsets.only(left: 50 ,right: 50),
        child:FutureBuilder<Map<String, dynamic>>(
        future: fetchData, // async work
        builder: (context,snapshot) {
           switch (snapshot.connectionState) {
             case ConnectionState.waiting: return new Center(child: Text('Loading....'));
             default:
               if (snapshot.hasError)
                  return Text("Error!");
               else{
              data = snapshot.data;
              return ListView(
          children: <Widget>[
            Center(
              child: Text(data[3]['Head']),
            ),
            Center(
              child: Text(data[0]['Description']),
            ),
            Image.network(data[0]['ImgUrl']),

          ],
        )}
            }
         },
        ),
      )
    );
  }
}

答案 2 :(得分:0)

您的fetchData()函数是异步的,因此您的应用点击函数的背面,说“嗨,fetchData()开始工作!”但是您的应用会继续关注自己的工作。

您为此做了工作:

              child: Text(data[3]['Head']),

因此,您的应用将按以下代码行显示,而您的data变量仍然为空列表。

您必须为这种情况做好准备。您可以准备数据的默认值,也可以检查依赖于它的窗口小部件中的数据是否为空。