import 'package:http/http.dart' as http;
import 'package:teste3/Post.dart';
import 'dart:convert';
import 'dart:async';
class Consumo extends StatefulWidget {
const Consumo({Key? key}) : super(key: key);
@override
State<Consumo> createState() => _ConsumoState();
}
class _ConsumoState extends State<Consumo> {
var _urlBase = Uri.parse("https://jsonplaceholder.typicode.com");
Future<List<Post>> _recuperarPostagens() async {
http.Response response = await http.get( _urlBase "/posts" );
var dadosJson = json.decode( response.body );
List<Post> postagens = [];
for( var post in dadosJson ){
print("post: " post["title"] );
Post p = Post(post["userId"], post["id"], post["title"], post["body"]);
postagens.add( p );
}
return postagens;
//print( postagens.toString() );
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Teste"),
),
body: FutureBuilder<Map>(
future: _recuperarPostagens(),
builder: (context, snapshot){
switch(snapshot.connectionState){
case ConnectionState.none:
case ConnectionState.waiting:
print("conexao waiting");
break;
case ConnectionState.active:
case ConnectionState.done:
print("conexao done");
if(snapshot.hasError){
}else {
}
}
return Center(
child: Text("teste"),
);
},
)
);
}
}
Console Error:
Error: The operator ' ' isn't defined for the class 'Uri'.
- 'Uri' is from 'dart:core'.
Try correcting the operator to an existing operator, or defining a ' ' operator.
http.Response response = await http.get( _urlBase "/posts" );
and:
Error: The argument type 'Future<List>' can't be assigned to the parameter type 'Future<Map<dynamic, dynamic>>?'.
'Future' is from 'dart:async'.
'List' is from 'dart:core'.
'Post' is from 'package:mood3/Post.dart' ('lib/Post.dart').
'Map' is from 'dart:core'.
future: _recuperarPostagens(), ^
Can somebody help me?
CodePudding user response:
You cannot concatenate Uris with the ' ' operator.
Change
var _urlBase = Uri.parse("https://jsonplaceholder.typicode.com");
to
String _urlBase = "https://jsonplaceholder.typicode.com";
and change
http.Response response = await http.get( _urlBase "/posts" );
to
http.Response response = await http.get( Uri.parse('$_urlBase/posts') );
CodePudding user response:
Try this:
const String _baseUrl = 'jsonplaceholder.typicode.com';
Uri uri = Uri.https(_baseUrl, '/posts');
final response = await http.get(uri);