从API获取数据并传递到下一页,但显示错误。

huangapple go评论60阅读模式
英文:

fetching data from api and pass it to next page but showing error

问题

//sign() fnction is in statless widget 
var y
y=signIn(); 
 Navigator.of(context).push(
                         MaterialPageRoute(
                           builder: (context) =>  posting(y),
                         ),
                       );

Future<Response?> signIn() async {
  var dio = Dio();
  try {
    var response = await dio.post('https://cisfapp.cisf.gov.in/abc/post.php',
        data: {
          "method"  : "posting",
          "username" : 1652356789
        },
        options: Options(
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            }
        ));
    Map mapResponse = {};
    mapResponse = jsonDecode(response.data);
    var x = mapResponse['data'][2]['unit_name'];
    print(x); //want to pass the value of x to next page 

    return response;
  } catch (e) {
    print(e.toString());
  }
  return null;
}

输出的程序按照我的理解是正常工作的。

请检查图像,它显示的是 Instance of 'Future<Response<dynamic>?>'

API 的输出如下:

{
   "message":"success",
   "err-code":"0",
   "data":
	 [
            {
              "unit_name":"alpha",
              "from_date":"2010-04-01 00:00:00",
              "sector_name":"TRG"
            },
            {
              "unit_name":"Bravo",
              "from_date":"2018-03-10 00:00:00",
              "sector_name":"Eastern"
            },
            {
              "unit_name":"charlie",
              "from_date":"2020-05-09 00:00:00",
              "sector_name":"western"
            }
         ]
}

我想要的是输出 API 的索引为 [2] 的 unit_name 的特定值,即 "charlie"。如果有人能帮忙,那就太好了。

英文:
//sign() fnction is in statless widget 
var y
y=signIn(); 
 Navigator.of(context).push(
                         MaterialPageRoute(
                           builder: (context) =&gt;  posting(y),
                         ),
                       );

Future&lt;Response?&gt; signIn() async {
  var dio = Dio();
  try {
    var response = await dio.post(&#39;https://cisfapp.cisf.gov.in/abc/post.php&#39;,
        data: {
          &quot;method&quot;  : &quot;posting&quot;,
          &quot;username&quot; : 1652356789
        },
        options: Options(
            headers: {
              &#39;Content-Type&#39;: &#39;application/json&#39;,
              &#39;Accept&#39;: &#39;application/json&#39;
            }
        ));
    Map mapResponse = {};
    mapResponse = jsonDecode(response.data);
    var x = mapResponse[&#39;data&#39;][2][&#39;unit_name&#39;];
    print(x); //want to pass the value of x to next page 

    return response;
  } catch (e) {
    print(e.toString());
  }
  return null;
}

this is the output of above program which is properly working according to me

please check in image,it is showing Instance of 'Future&lt;Response&lt;dynamic&gt;?&gt;

api output is :-
{
"message":"success",
"err-code":"0",
"data":
[
{
"unit_name":"alpha",
"from_date":"2010-04-01 00:00:00",
"sector_name":"TRG"
},
{
"unit_name":"Bravo",
"from_date":"2018-03-10 00:00:00",
"sector_name":"Eastern"
},
{
"unit_name":"charlie",
"from_date":"2020-05-09 00:00:00",
"sector_name":"western"
}
]

}
i want the specific value of unit_name which is "charlie" and which is at index [2] of output api......help pls if anyone can

答案1

得分: 1

使用await关键字等待API响应。

var y
y.then(result =&gt; {
   Navigator.of(context).push(MaterialPageRoute(
        builder: (context) =&gt; posting(result),),);
  }).catch(error =&gt; {
});
Future&lt;String?&gt; signIn() async {
    var dio = Dio();
    try {
      var response = await dio.post(&#39;https://cisfapp.cisf.gov.in/abc/post.php&#39;,
          data: {
            &quot;method&quot; : &quot;posting&quot;,
            &quot;username&quot; : 1652356789
          },
          options: Options(
              headers: {
                &#39;Content-Type&#39;: &#39;application/json&#39;,
                &#39;Accept&#39;: &#39;application/json&#39;
              }
          ));
      Map mapResponse = response.data as Map&lt;dynamic, dynamic&gt;;
      return mapResponse[&#39;data&#39;][2][&#39;unit_name&#39;];
    } catch (e) {
      print(e.toString());
    }
    return null;
  }
英文:

Use await keyword for wait for response from API.

    var y
    y.then(result =&gt; {
       Navigator.of(context).push(MaterialPageRoute(
            builder: (context) =&gt; posting(result),),);
      }).catch(error =&gt; {
    });


Future&lt;String?&gt; signIn() async {
    var dio = Dio();
    try {
      var response = await dio.post(&#39;https://cisfapp.cisf.gov.in/abc/post.php&#39;,
          data: {
            &quot;method&quot; : &quot;posting&quot;,
            &quot;username&quot; : 1652356789
          },
          options: Options(
              headers: {
                &#39;Content-Type&#39;: &#39;application/json&#39;,
                &#39;Accept&#39;: &#39;application/json&#39;
              }
          ));
      Map mapResponse = response.data as Map&lt;dynamic, dynamic&gt;;
      return mapResponse[&#39;data&#39;][2][&#39;unit_name&#39;];
    } catch (e) {
      print(e.toString());
    }
    return null;
  }

答案2

得分: 1

以下是您要翻译的内容:

错误可能是因为 signIn() 返回一个 Future<String?>,但您试图将未来的结果(一个字符串)传递给构造函数。相反,您应该等待未来完成,然后将结果传递给构造函数。您可以使用 await 关键字来实现这一点。以下是一个示例:

var response = await signIn(); // 等待 signIn() 完成并获取响应
Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => posting(response), // 将响应数据传递给构造函数
  ),
);
Future<String?> signIn() async {
  var dio = Dio();
  try {
    var response = await dio.post('https://cisfapp.cisf.gov.in/abc/post.php',
        data: {"method": "posting", "username": 1652356789},
        options: Options(headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }));
    Map mapResponse = {};
    mapResponse = jsonDecode(response.data);
    var x = mapResponse['data'][2]['unit_name'];
    return x;
  } catch (e) {
    print(e.toString());
  }
  return null;
}

另外,请确保您正确处理错误。如果从 API 获取数据时出现错误,signIn() 将返回 null。您应该处理这种情况,并向用户显示适当的错误消息。

英文:

The error may be because signIn() returns a Future<String?> but you are trying to pass the result of the future (which is a String?) to the posting constructor. Instead, you should wait for the future to complete and then pass the result to the constructor. You can do this using the await keyword. Here's an example:

var response = await signIn(); // wait for signIn() to complete and get the response
Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) =&gt; posting(response), // pass the response data to the constructor
  ),
);

  Future&lt;String?&gt; signIn() async {
var dio = Dio();
try {
  var response = await dio.post(&#39;https://cisfapp.cisf.gov.in/abc/post.php&#39;,
      data: {&quot;method&quot;: &quot;posting&quot;, &quot;username&quot;: 1652356789},
      options: Options(headers: {
        &#39;Content-Type&#39;: &#39;application/json&#39;,
        &#39;Accept&#39;: &#39;application/json&#39;
      }));
  Map mapResponse = {};
  mapResponse = jsonDecode(response.data);
  var x = mapResponse[&#39;data&#39;][2][&#39;unit_name&#39;];
  return x;
} catch (e) {
  print(e.toString());
}
return null;

}

Also, make sure that you are handling errors properly. If there is an error while fetching data from the API, signIn() will return null. You should handle this case and show an appropriate error message to the user.

答案3

得分: 0

以下是已翻译的内容:

你可以尝试这样做,或者只是使用 await

var y;
y = signIn();
y.then(result => {
    Navigator.of(context).push(
        MaterialPageRoute(
            builder: (context) => posting(result),
        ),
    );
}).catch(error => {
});
英文:

You can try this, or simply using await

var y;
y = signIn();
y.then(result =&gt; {
    Navigator.of(context).push(
        MaterialPageRoute(
            builder: (context) =&gt; posting(result),),);

}).catch(error =&gt; {
});

huangapple
  • 本文由 发表于 2023年4月11日 12:29:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定