Flutter: snapshot.data does not load Json value

Asked

Viewed 54 times

2

I’m creating a code for a Udemy course that I can’t get the answer to code that works on the teacher’s machine. I tried to change the versions, but apparently, the error is in the request response when I need to get the snapshot.datavalue. If I ask to print, he accepts nicely and printa on the console. But if I want to access the sale value for example of the currency I will make the request, gives error.

This is my code:

 import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
 
const request = "https://api.hgbrasil.com/finance?key=687c4baa";
 
void main () async {
  http.Response responses = await http.get(Uri.parse(request));
  print(jsonDecode(responses.body)["results"]["currencies"]["USD"]["buy"]);
 
  runApp(MaterialApp(
      home: home()
  ));
}
 
Future<Map> getData() async {
  http.Response response = await http.get(Uri.parse(request));
  return jsonDecode(response.body);
}
 
class home extends StatefulWidget {
  const home({Key? key}) : super(key: key);
 
  @override
  _homeState createState() => _homeState();
}
 
class _homeState extends State<home> {
 
  // as variaveis do problema
  double dolar;
  double euro;
  /*
A solução que achei
 
  double? dolar;
  double? euro;
 
  * */
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar (
        title: Text("\$ Conversor \$"),
        backgroundColor: Colors.amber,
        centerTitle: true,
      ),
      body:
      // Esse map constrói uma parte do texto quando tiver pronto dependendo do que tiver dentro do parâmetro future.
      FutureBuilder<Map>(
        future: getData(),
        //cria uma função anônima que vai passar o estado do request
        builder: (context, snapshot){
          switch(snapshot.connectionState){
            case ConnectionState.none:
            case ConnectionState.waiting:
              return Center(
                child: Text("Carregando dados...", style: TextStyle(
                    color: Colors.green,
                    fontSize: 25),
                  textAlign: TextAlign.center,),
              );
            default: if (snapshot.hasError){
              return Center(
                child: Text("Erro ao carregar dados :(", style: TextStyle(
                    color: Colors.green,
                    fontSize: 25),
                  textAlign: TextAlign.center,),
              );
            } else {
              print(snapshot.data);
              //dolar = snapshot.data["results"]["currencies"]["USD"]["buy"];
              // euro = snapshot.data["results"]["currencies"]["EUR"]["buy"];
 
              return Center(
                child: Text("Tudo certo :(", style: TextStyle(
                    color: Colors.green,
                    fontSize: 25),
                  textAlign: TextAlign.center,),
              );
            }
          }
        },
      ),
    );
  }
}

begins the problem by calling the double dollar and euro without defined value.

class _homeState extends State<home> {
 
  // as variaveis do problema
  double dolar;
  double euro;

In addition. In the end, it returns the json in the snapshot.data , so much so that I can even print it:

print(snapshot.data);

Only, if I decode the requests,

//dolar = snapshot.data["results"]["currencies"]["USD"]["buy"];
// euro = snapshot.data["results"]["currencies"]["EUR"]["buy"];

He makes a mistake in both the euro and the dollar.

### Respost do RUN do Android Studio.
Error: Operator '[]' cannot be called on 'Map<dynamic, dynamic>?' because it is potentially null.
 - 'Map' is from 'dart:core'.
              euro = snapshot.data["results"]["currencies"]["EUR"]["buy"];

I tried to use different versions in pubspec of both the HTTP and sdk packages. Currently:

environment:
  sdk: ">=2.12.0 <3.0.0"
 
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  http: any #^0.12.0+2

I have tried to put the sdk at 2.7.0 < 3.0.0 as suggested...

I tried to use http on 0.12.0+2, but whenever I use it, it reports error in the - package:http and - package:http_parser command

Launching lib\main.dart on AOSP on IA Emulator in debug mode...
Running Gradle task 'assembleDebug'...
Error: Cannot run with sound null safety, because the following dependencies
don't support null safety:
 
 - package:http
 - package:http_parser
 
For solutions, see https://dart.dev/go/unsound-null-safety
lib/main.dart:75:36: Error: Operator '[]' cannot be called on 'Map<dynamic, dynamic>?' because it is potentially null.
 - 'Map' is from 'dart:core'.
              dolar = snapshot.data["results"]["currencies"]["USD"]["buy"];
                                   ^
lib/main.dart:76:35: Error: Operator '[]' cannot be called on 'Map<dynamic, dynamic>?' because it is potentially null.
 - 'Map' is from 'dart:core'.
              euro = snapshot.data["results"]["currencies"]["EUR"]["buy"];
                                  ^
 
 
FAILURE: Build failed with an exception.
 
* Where:
Script 'E:\Aplicativos\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1035
 
* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'E:\Aplicativos\flutter\bin\flutter.bat'' finished with non-zero exit value 1
 
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
 
* Get more help at https://help.gradle.org
 
BUILD FAILED in 9s
Exception: Gradle task assembleDebug failed with exit code 1

and if I go back to http: any, the error turns into that monster I’ve said before:

Launching lib\main.dart on AOSP on IA Emulator in debug mode...
Running Gradle task 'assembleDebug'...
lib/main.dart:75:36: Error: Operator '[]' cannot be called on 'Map<dynamic, dynamic>?' because it is potentially null.
 - 'Map' is from 'dart:core'.
              dolar = snapshot.data["results"]["currencies"]["USD"]["buy"];
                                   ^
lib/main.dart:76:35: Error: Operator '[]' cannot be called on 'Map<dynamic, dynamic>?' because it is potentially null.
 - 'Map' is from 'dart:core'.
              euro = snapshot.data["results"]["currencies"]["EUR"]["buy"];
                                  ^
lib/main.dart:32:10: Error: Field 'dolar' should be initialized because its type 'double' doesn't allow null.
  double dolar;
         ^^^^^
lib/main.dart:33:10: Error: Field 'euro' should be initialized because its type 'double' doesn't allow null.
  double euro;
         ^^^^
 
 
FAILURE: Build failed with an exception.
 
* Where:
Script 'E:\Aplicativos\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1035
 
* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'E:\Aplicativos\flutter\bin\flutter.bat'' finished with non-zero exit value 1
 
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
 
* Get more help at https://help.gradle.org
 
BUILD FAILED in 9s
Exception: Gradle task assembleDebug failed with exit code 1

I tried to pass on as much information as possible. But I’m having a fit here. I’ve already asked for reimbursement of two courses because of these version differences drugs. This I am in the most updated that has, but even it is full of problems by broken versions.

  • Hi. If you can edit your question and insert which error it gives, and which print return, it would be helpful.

  • All right. I’ll put

  • I edited it. Thank you.

1 answer

3


From Dart 2.0 was included the Nullsafety that brings extra security to us while we are developing our application. Actually many courses are lagged at this point by being something more "current".

Regarding your problem, you only need to try to use the correct nullsafety.

1 - Point

Your various locations, you can state in two ways so that for sure.

  double? dolar;
  double? euro;

or

  double dolar = 0.0;
  double euro = 0.0;

In the first option, variables can receive null value.

2 - Point

The return of Futurebuilder can result you a null value, which is what the error message wants to tell you, so then you can have two outputs as well.

final Map data = snapshot.data!;
dolar = data["results"]["currencies"]["USD"]["buy"];
euro = data["results"]["currencies"]["EUR"]["buy"];

or

final Map data = snapshot.data;
if (data == null) {
  dolar = 0.0;
  euro = 0.0;
} else {
  dolar = data["results"]["currencies"]["USD"]["buy"];
  euro = data["results"]["currencies"]["EUR"]["buy"];
}

Explanation

Within the examples you can see some symbols:

double? -> "?" Indicates that the variable can receive a numerical value or have its value as NULL (NULL).

snapshot.data!-> "!" Indicates that that variable or property, even if it can be null, at that specific point you are sure that it will have a defined value in it other than NULL.

  • 1

    Thank you very much. With your support I studied more on the subject and solved. Thanks even.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.