I'm expecting a JSON object of data but instead am getting Instance of 'Post'
I'm new to flutter and trying to hit an API with a post request using http.dart package. I'm using an async future and a future building to populate a widget with the returned data (following the flutter example here: https://flutter.io/docs/cookbook/networking/fetch-data).
Future<Post> fetchPost() async {
String url = "https://example.com";
final response = await http.post(url,
headers: {HttpHeaders.contentTypeHeader: 'application/json'},
body: jsonEncode({"id": "1"}));
if (response.statusCode == 200) {
print('RETURNING: ' + response.body);
return Post.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load post');
}
}
class Post {
final String title;
Post({this.title});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
title: json['title']
);
}
}
void main() => runApp(MyApp(post: fetchPost()));
class MyApp extends StatelessWidget {
final Future<Post> post;
MyApp({Key key, this.post}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Post>(
future: post,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.toString());
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
),
),
),
);
}
}
I'm expecting the return statement in the FutureBuilder to give me a json object. This is an existing API so I know it works and it returns what I'm expecting.