I'm trying to return a json
string in Flutter
. I'm using the print
function to display the output in the console. However my code is returning the String
twice. Here is my code:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() => runApp(new HomePage());
class HomePage extends StatelessWidget {
Future<http.Response> fetchPost() async{
return await http.get('https://api.npoint.io/8c7aafe809d73af5f2b9');
}
void Data() async {
var jsonString = await fetchPost();
print(jsonString.body);
}
@override
Widget build(BuildContext context) {
Data();
return new MaterialApp(
home: new Center(
child: new Text('Data'),
),
);
}
}
Solution 1: Nassar
The build method is called twice causing the whole widget to be called again. Consider converting StatelessWidget
to StatefulWidget
and add your http call method in
@overridde
initState() {
your code
}
Solution 2: Fathah Cr
I had the same issue and solved using try
catch
Future<http.Response> fetchPost() async{
try{
return await http.get('https://api.npoint.io/8c7aafe809d73af5f2b9');
}
catch (e) {
print(e);
}
}