Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果json数据为空或json链接无效,是否可以显示颤振应用程序_Json_Dart_Flutter - Fatal编程技术网

如果json数据为空或json链接无效,是否可以显示颤振应用程序

如果json数据为空或json链接无效,是否可以显示颤振应用程序,json,dart,flutter,Json,Dart,Flutter,我有着陆颤振页面(main.dart)。我有JSON数据,我正在使用Future来获取它。 我的问题是,如果数据为null,或者JSON链接无效,我如何用空数据显示应用程序 我的问题是,我的Flitter应用程序的屏幕是白色的,然后它会随着显示CircularProgressIndicator而变黑。如果存在上述错误,则其将继续使用CircularProgressIndicator运行黑屏 当我的应用程序从第二秒启动时,我需要显示CircularProgressIndicator并执行其余操作。

我有着陆颤振页面(main.dart)。我有JSON数据,我正在使用Future来获取它。 我的问题是,如果数据为null,或者JSON链接无效,我如何用空数据显示应用程序

我的问题是,我的Flitter应用程序的屏幕是白色的,然后它会随着显示CircularProgressIndicator而变黑。如果存在上述错误,则其将继续使用CircularProgressIndicator运行黑屏

当我的应用程序从第二秒启动时,我需要显示CircularProgressIndicator并执行其余操作。如果JSON数据为null或链接无效,我仍然需要用空数据显示我的应用程序,并显示一些警告

// TODO: 4) _MyHomePageState Class
class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getCurrencyJsonData();
  }

  Future<String> getCurrencyJsonData() async {
    var response = await http.get(
        Uri.encodeFull("https://secure.*****************fx.jsp"),
        headers: {'Accept': 'application/json'});

    setState(() {
      var resBody = json.decode(response.body);
      currencyData = resBody["currency"];
      stgBuy = currencyData["sterling"]["buy"];
      print("STG: $stgBuy");
    });

    return "Success!";
  }


// TODO: BUILD WIDGET
  @override
  Widget build(BuildContext context) {
    if (currencyData == null){
      return new Center(
          child: new CircularProgressIndicator(
            backgroundColor: lightMainGreen,
          )
      );
    } else {

      return new Scaffold(
        // APPBAR
        appBar: new AppBar(
          title: new Text(
    …… 
    ……
    ……
//TODO:4)\u MyHomePageState类
类_MyHomePageState扩展状态{
@凌驾
void initState(){
//TODO:实现initState
super.initState();
这个.getCurrencyJsonData();
}
Future getCurrencyJsonData()异步{
var response=wait http.get(
Uri.encodeFull(“https://secure.*****************fx.jsp”),
标题:{'Accept':'application/json'});
设置状态(){
var resBody=json.decode(response.body);
currencyData=resBody[“货币”];
stgBuy=货币数据[“英镑”][“买入”];
打印(“STG:$stgBuy”);
});
返回“成功!”;
}
//TODO:构建小部件
@凌驾
小部件构建(构建上下文){
if(currencyData==null){
返回新中心(
儿童:新的循环压缩机指示器(
背景颜色:浅绿色,
)
);
}否则{
归还新脚手架(
//APPBAR
appBar:新的appBar(
标题:新文本(
…… 
……
……

好的,根据@günter-zöchbauer的建议,我使用了一个FutureBuilder解决了我的问题。下面是完整的代码部分:

// TODO: 4) _MyHomePageState Class
class _MyHomePageState extends State<MyHomePage> {


// TODO: BUILD WIDGET
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        // APPBAR
        appBar: new AppBar(
          title: new Text("main.appTitle"),
            style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.w500),
          ),
          backgroundColor: midMainGreen,
        ),
        drawer: new DrawerMenu(),

        // BODY
        body: new Center(
          child: new FutureBuilder(
              future: getCurrencyJsonData(),
              builder: (context, snaphot) {
                if (snaphot.hasData) {
                  return new ListView(
                    padding: const EdgeInsets.all(0.0),
                    children: <Widget>[
                      new MainHeader(),
                      new Padding(
                          padding: EdgeInsets.fromLTRB(3.0, 4.0, 3.0, 4.0)),
                      new CurrencyCard(),
                      new LandingListMenu(),
                    ],
                  );
                }
                return new CircularProgressIndicator();
              }),
        ));
  } // build Widget
} // 4) _MyHomePageState Class


    Future<String> getCurrencyJsonData() async {

  var response = await http.get(
      Uri.encodeFull("https://secure.*****************fx.jsp"),
      headers: {'Accept': 'application/json'});

  if (response.statusCode == 200) {
     var resBody = json.decode(response.body);
     currencyData = resBody["currency"];
     if (currencyData != null) {
        stgBuy = currencyData["sterling”][“alis"];

     } else {
        stgBuy = "0.0000";
     }
  } else {
    stgBuy = "0.0000";
  }


  return "Success!";
}
//TODO:4)\u MyHomePageState类
类_MyHomePageState扩展状态{
//TODO:构建小部件
@凌驾
小部件构建(构建上下文){
归还新脚手架(
//APPBAR
appBar:新的appBar(
标题:新文本(“main.appTitle”),
样式:TextStyle(fontSize:18.0,fontWeight:fontWeight.w500),
),
背景颜色:中绿色,
),
抽屉:新抽屉菜单(),
//身体
正文:新中心(
孩子:新未来建设者(
future:getCurrencyJsonData(),
生成器:(上下文,snaphot){
if(snaphot.hasData){
返回新的ListView(
填充:常量边集全部(0.0),
儿童:[
新建MainHeader(),
新填料(
填充:来自LTRB(3.0、4.0、3.0、4.0)的边集,
新的货币卡(),
新建LandingListMenu(),
],
);
}
返回新的循环ProgressIndicator();
}),
));
}//构建小部件
}//4)\u MyHomePageState类
Future getCurrencyJsonData()异步{
var response=wait http.get(
Uri.encodeFull(“https://secure.*****************fx.jsp”),
标题:{'Accept':'application/json'});
如果(response.statusCode==200){
var resBody=json.decode(response.body);
currencyData=resBody[“货币”];
if(currencyData!=null){
stgBuy=货币数据[“英镑”][“alis”];
}否则{
stgBuy=“0.0000”;
}
}否则{
stgBuy=“0.0000”;
}
返回“成功!”;
}

您可以在
getCurrencyData()
中处理错误。然后在
build()
中检查是否收到错误

Future<Map<String, dynamic>> getCurrencyJsonData() async (
  try {
    http.Response response = await http.get(url);
    if (response.statusCode == 200) {
      return {"success": json.decode(response.body)};
    }
    // Bad Request
    else if (response.statusCode == 400) {
      return {"error": "Bad request"};
    } else if (response.statusCode == 401) {
      return {"error": "Unauthorized"};
    }
  } on Exception {
    return {"error": "Some exception"};
  }
  setState(() {});
}

@override
Widget build(BuildContext context) {
if (currencyData == null){
  return new Center(
      child: new CircularProgressIndicator(
        backgroundColor: lightMainGreen,
      )
  );
} else if (currencyData.containsKey("error")){
  return new ErrorScaffold(
  ...)
} else {

  return new Scaffold(
  .....
Future getCurrencyJsonData()异步(
试一试{
http.Response-Response=等待http.get(url);
如果(response.statusCode==200){
返回{“success”:json.decode(response.body)};
}
//错误的请求
else if(response.statusCode==400){
返回{“错误”:“错误请求”};
}else if(response.statusCode==401){
返回{“error”:“Unauthorized”};
}
}例外{
返回{“error”:“someexception”};
}
setState((){});
}
@凌驾
小部件构建(构建上下文){
if(currencyData==null){
返回新中心(
儿童:新的循环压缩机指示器(
背景颜色:浅绿色,
)
);
}else if(currencyData.containsKey(“错误”)){
返回新的错误脚手架(
...)
}否则{
归还新脚手架(
.....

@chemamolis,我使用FutureBuilder解决了我的问题。我将使用您的响应状态代码并更新我的答案。谢谢。