【问题标题】:Flutter: response variable blank in http requestFlutter:http请求中的响应变量为空
【发布时间】:2021-03-02 11:58:44
【问题描述】:

我正在尝试为我的 Flutter 应用创建个人资料页面 这是一个sn-p

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

class MyProfile extends StatefulWidget {


  @override
  _MyProfileState createState() => _MyProfileState();
}

class _MyProfileState extends State<MyProfile> {
  bool visible=false;
  var postData=List();
  var jsonData;
  Future accountInfo()async{
    
    var url ='http://192.168.0.107/get_account.php';
    var response= await http.get(url);
    var jsonData= json.decode(response.body);
    setState(() { 
      postData=jsonData;
    });
    debugPrint(jsonData);
    return jsonData;
    }
    
    @override
    void initState(){
      super.initState();
      accountInfo();
    }

但是,变量 postData 和 jsonData 返回为 null。 postData的值=[]

API 运行良好,使用邮递员进行了尝试,还尝试使用代理工具进行拦截。 我得到一个有效的 json 响应正文。但是这些值不会传递到 jsonData 或 postData。

当我在文本小部件中使用 postData 时,我收到此错误:- RangeError(index):索引超出范围:没有有效的索引:0

【问题讨论】:

  • 响应也为空吗?和 response.body 分别?
  • no response.body 显然返回了所需的 json。也使用代理对其进行了验证
  • response.body 不为空,但是在调试 jsonData 的值时出现以下错误 ERROR:flutter/lib/ui/ui_dart_state.cc(166)] 未处理的异常:类型 '_InternalLinkedHashMap' 不是类型 'String 的子类型

标签: flutter dart flutter-test


【解决方案1】:

你定义了两个 jsonData。这可能是原因。另外,也在 setState() 中设置 jsonData。试试这个:

var jsonData;
Future accountInfo()async{
  setState(() {
    visible=true;
  });
  var url ='http://192.168.0.107/get_account.php';
  var response = await http.get(url);
  
  setState(() { 
    jsonData = json.decode(response.body); // Here we changed!
    postData = jsonData;
  });

【讨论】:

  • 试过了,还是出现 RangeError
【解决方案2】:

解决方法是将jsonData定义为

Map<String, dynamic> jsonData= jsonDecode(response.body);

【讨论】:

    猜你喜欢
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    相关资源
    最近更新 更多