简体   繁体   English

snapshot.data 是 Flutter 中的 null

[英]snapshot.data is null in Flutter

My snapshot.data is null.我的 snapshot.data 是 null。 When I print the response it is displaying the retrieved data.当我打印响应时,它显示检索到的数据。 But still snapshot.data is null.但仍然 snapshot.data 是 null。

    Future _getUsers() async {
         
        var data = await http.post("http://10.0.2.2/Flutter/abreport.php", body: {
        {
          "date": mydt,
         });
         var jsonData = json.decode(data.body); //edited
         print(jsonData); // the data is printing here

         return jsonData;
       }  
    
       }  

    FutureBuilder(
            future: _getUsers(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
                  debugPrint(snapshot.data);
              if (snapshot.data == null) {
                return Container(
                  child: Center(
                
                    child:Text("no data"),
                    )
                    );
              } else {
                 //some code
             }

              ) 

You should use the format given in the documentation for FutureBuilder .您应该使用FutureBuilder 文档中给出的格式。 You're not checking for the state of the future, so when the FutureBuilder is first built, it will display "no data" .您不是在检查未来的状态,因此在首次构建FutureBuilder时,它将显示"no data" You haven't implemented your else branch, so by the time you have data, your build will probably not refresh anyway.你还没有实现你的else分支,所以当你有数据时,你的构建可能无论如何都不会刷新。 Try this code instead:试试这个代码:

FutureBuilder(
  future: _getUsers(),
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.data == null) {
        return Text('no data');
      } else {
        return Text('data present');
      }
    } else if (snapshot.connectionState == ConnectionState.error) {
      return Text('Error'); // error
    } else {
      return CircularProgressIndicator(); // loading
    }
  }
)

with Flutter 2.2, this one returns an error使用 Flutter 2.2,这个返回错误

builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
  if (snapshot.hasData) {
    return Text(snapshot.data,);

Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.
return Text(snapshot.data,);

but this one dosen't但这个没有

builder: (BuildContext context, AsyncSnapshot snapshot) {

When similar things happen, take the type "var" not "String" or other non-nullable type.当类似的事情发生时,取类型“var”而不是“String”或其他不可为空的类型。 (If it was not Flutter, the compilers will do?) (如果不是 Flutter,编译器会做吗?)

Since i cannot see your complete code, i am assuming you are parsing your json data incorrectly after receiving it inside FutureBuilder.由于我看不到您的完整代码,我假设您在 FutureBuilder 中接收到您的 json 数据后解析错误。 Below is an example which is similar to what you are doing.下面是一个与您正在执行的操作类似的示例。 This example retrieves Date json data and displays using FutureBuilder,此示例检索日期 json 数据并使用 FutureBuilder 显示,

import 'dart:convert';

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

void main() {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: Center(
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Padding(
                          padding: const EdgeInsets.only(left: 10.0, right: 10.0),
                          child: FutureBuilder(
                            future: _getDate(),
                            builder: (BuildContext context, AsyncSnapshot snapshot) {
                              if (snapshot.hasData) {
                                return Text('Date: ' + snapshot.data['date']
                                    + '\nMilliseconds Since Epoch: ' + snapshot.data['milliseconds_since_epoch'].toString()
                                + '\nTime: ' + snapshot.data['time'],
                                style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold, color: Colors.grey));
                              } else {
                                return Center(child: CircularProgressIndicator());
                              }
                            },
                          ))
        ]))));
  }

  Future _getDate() async {
    var data = await http.post("http://date.jsontest.com/");
    var jsonData = json.decode(data.body);
    print(jsonData);

    return jsonData;
  }
}

Test screenshot:测试截图:

测试截图

Hope this helps.希望这可以帮助。

Because your async function doesnt return anything.. Change it like this:因为您的异步 function 没有返回任何内容.. 像这样更改它:

 Future _getUsers() async {
         
        return await http.post("http://10.0.2.2/Flutter/abreport.php", body: {
        {
          "date": mydt,
         });
         var jsonData = json.decode(data.body); //edited
         print(jsonData); // the data is printing here

         return jsonData;
       }  
    
       }  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM