Tô criando um código de um curso da Udemy que não consigo obter a resposta do código que funciona na máquina do professor. Tentei mudar as versões, mas ao que parece, o erro está na resposta da requisição quando preciso pegar o valor de snapshot.data. Seu eu pedir pra printar, ele aceita de boa e printa no console. Mas se eu quiser acessar o valor de venda por exemplo da moeda que vou fazer a requisição, dá erro.
Esse é o meu código:
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,),
);
}
}
},
),
);
}
}
começa o problema por chamar o double dolar e euro sem valor definido.
class _homeState extends State<home> {
// as variaveis do problema
double dolar;
double euro;
Além. No final, ele me retorna o json no snapshot.data , tanto que eu posso até printar ele:
print(snapshot.data);
Só que, se eu descomentar os requests,
//dolar = snapshot.data["results"]["currencies"]["USD"]["buy"];
// euro = snapshot.data["results"]["currencies"]["EUR"]["buy"];
Ele dá erro tanto no euro quanto no dolar.
### 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"];
Tentei usar diferentes versões no pubspec tanto do pacote HTTP quanto do sdk. Atualmente está:
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
http: any #^0.12.0+2
Já tentei colocar do sdk em 2.7.0 < 3.0.0 como sugeriram...
tentei usar o http no ^0.12.0+2, mas sempre que uso ele, ele informa erro no comando - package:http e - package:http_parser
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
e se volto para o http: any, o erro vira esse monstro que já falei antes:
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
Tentei passar o máximo de informações possíveis. Mas tô tendo um treco aqui. Já pedi reembolso de dois cursos por causa dessas drogas de diferenças de versões. Isso que eu estou no mais atualizado que tem, mas mesmo ele tá cheio de problemas por versões quebradas.