【问题标题】:Flutter Getting snapshot.hasError颤振获取快照.hasError
【发布时间】:2022-01-14 04:36:33
【问题描述】:

尝试从 api 获取数据,当我尝试使用该数据时,我得到了 snapshot.hasError。 snapShot.hasError 是 Null 不是“String”类型的子类型,不确定问题出在哪里,所以任何帮助都会不胜感激,这是我正在使用的两个文件以及我从 api 获得的数据

dataset_forKuiz.dart

Future<List<KuizData>?> fetchData2() async {
  String username = 'hello';
  String password = 'hello';
  String basicAuth = base64Encode(utf8.encode('$username:$password'));
  print("BASOICCCCCCCCPPPPP $basicAuth");
  var url = "https://fm-srvc.herokuapp.com/api/order-words";
  var response = await http.get(
    Uri.parse(url),
    headers: {
      HttpHeaders.authorizationHeader: 'Basic $basicAuth',
    },
  );
  print("Hellooo ${response.statusCode}");
  if (response.statusCode == 200) {
    List data2 = json.decode(utf8.decode(response.bodyBytes));
    return data2.map((data) => KuizData.fromJson(data)).toList();
  } else {
    throw Exception('Unexpected error occured');
  }
}

class KuizData {
  int level;
  String question;
  List options;
  String answer;
  int time;

  KuizData(
      {required this.level,
      required this.question,
      required this.options,
      required this.answer,
      required this.time});

  factory KuizData.fromJson(Map<String, dynamic> json) {
    return KuizData(
        level: json['level'],
        question: json['question'],
        options: json['options'],
        answer: json['answer'],
        time: json['time']);
  }
}

kuizi.dart

class Kuizi extends StatefulWidget {
  const Kuizi({Key? key}) : super(key: key);

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

class _KuiziState extends State<Kuizi> {
  late Future<List<KuizData>?> futureData2;

  void initState() {
    super.initState();
    futureData2 = fetchData2();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            automaticallyImplyLeading: false,
            toolbarHeight: 60,
            backgroundColor: Color(0xFF0A869B),
            title: Row(children: <Widget>[
              IconButton(
                  icon: const Icon(Icons.arrow_back),
                  color: Colors.white,
                  onPressed: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => RenditFjaletScreen()));
                  }),
              Padding(
                  padding: const EdgeInsets.only(left: 40),
                  child: Align(
                      alignment: Alignment.topCenter,
                      child: Text('Kuizi',
                          style: GoogleFonts.fredokaOne(
                              textStyle: TextStyle(fontSize: 30)))))
            ])),
        body: FutureBuilder<List<KuizData>?>(
            future: futureData2,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<KuizData>? data = snapshot.data;
                data?.sort((a, b) => a.level.compareTo(b.level));

                return Stack(children: [
                  Container(
                      decoration: BoxDecoration(
                          image: DecorationImage(
                              image: AssetImage(
                                'assets/background.PNG',
                              ),
                              fit: BoxFit.cover)),
                      child: Padding(
                          padding: const EdgeInsets.all(12.0),
                          child: GridView.count(
                              crossAxisCount: 4,
                              children: List.generate(data!.length, (index) {
                                return InkWell(
                                    splashColor: Colors.blue.withAlpha(20),
                                    onTap: () {

                                    },
                                    child: Card(
                                        elevation: 3.0,
                                        margin: EdgeInsets.all(7.0),
                                        shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(20.0)),
                                        child: Container(
                                            child: Align(
                                                alignment: Alignment.center,
                                                child: Container(
                                                    child: Text(
                                                        '${data[index].level}',
                                                        style: GoogleFonts.fredokaOne(
                                                            textStyle: TextStyle(
                                                              fontSize: 30.0.sp,
                                                              color: Color(0xFF50CFFD),
                                                            ))
                                                    )
                                                ))
                                        )
                                    )
                                );
                              })
                          )
                      ))
                ]);
              } else if (snapshot.hasError) {
                return Text("OO ILAZZZ ${snapshot.error}");
              }
              return Center(child: CircularProgressIndicator());
            }));
  }
}

来自 api 的数据

"id": "1c2ef15c-6dec-4bab-968e-d3a9ab48f897",
        "level": 1,
        "question": "Cili është urdhri më i rëndësishëm?",
        "options": [
            "Teuhidi.",
            "Namazi.",
            "Adhurimi.",
            "Agjërimi."
        ],
        "answer": "Teuhidi.",
        "time": 65,
        "updatedAt": "2020-07-09T06:38:08.222990Z"
    },

【问题讨论】:

  • 在 initistate 中调用 getData() 时得到的响应代码是什么?
  • 你在哪里看到 initstate 中的 getData
  • 对不起,futureData2 = fetchData2();
  • 响应状态码为200
  • 基本身份验证工作正常,只是在屏幕上显示快照有错误错误

标签: flutter dart flutter-layout flutter-dependencies


【解决方案1】:

您的 Future 函数需要 List&lt;KuizData&gt; 但您只传递了单个对象。对您的 dataset_forKuiz.dart 文件进行以下更改

//create this function to return List of KuizData
List<KuizData> list(data) => List.from(data).map((e) => KuizData.fromJson(e)).toList();

Future<List<KuizData>?> fetchData2() async {
  String username = 'hello';
  String password = 'hello';
  String basicAuth = base64Encode(utf8.encode('$username:$password'));
  print("BASOICCCCCCCCPPPPP $basicAuth");
  var url = "https://fm-srvc.herokuapp.com/api/order-words";
  var response = await http.get(
    Uri.parse(url),
    headers: {
      HttpHeaders.authorizationHeader: 'Basic $basicAuth',
    },
  );
  print("Hellooo ${response.statusCode}");
  if (response.statusCode == 200) {
    List data2 = json.decode(utf8.decode(response.bodyBytes));
    return list(response.bodyBytes); // this will return a list as expected
  } else {
    throw Exception('Unexpected error occured');
  }
}

【讨论】:

  • 现在我得到一个快照 hasError 像这样:发生意外错误
  • 你试过我的代码了吗?
  • 是的,现在状态是 401
  • 使用我之前尝试过的代码,我得到了 200 状态,但出现了另一个错误
  • 哦等等我忘了更改授权
【解决方案2】:

您期望一个列表。您的 JSON 数据只是一个数据点,而不是一个列表。修复您的数据或修复您的代码。

当您使用它时,Future&lt;List&lt;KuizData&gt;?&gt; fetchData2() 应该真的是Future&lt;List&lt;KuizData&gt;&gt; fetchData2(),因为您实际上永远不会返回 null。这将为您节省很多? 和“!”的麻烦。零安全并不容易,不要让它变得比自己更难。

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2021-10-23
    • 2022-06-28
    • 2020-05-02
    • 2021-03-17
    • 2021-07-05
    相关资源
    最近更新 更多