Inconsistent behavior of HttpServer in Flutter/Dart ! The following code runs fine if executed as a desktop application but returns an error as Unsupported Operation at ServerSocket.bind if executed as a web server or through browser !
import 'package:flutter/material.dart';
import 'dart:io';
void main()
{
runApp(MaterialApp(home: Home(),));
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
String statusText = "Start Server";
startServer()
async{
setState(() {
statusText = "Starting server on Port : 8088";
});
print("Attempting bind");
// other attempts with same result
// var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8088, shared: true);
// var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8089, shared: true);
// var server = await HttpServer.bind(InternetAddress.anyIPv4, 0, shared: true);
// var server = await HttpServer.bind("0.0.0.0", 35568, shared: true);
var serverSocket = await ServerSocket.bind("0.0.0.0", 0);
var server = HttpServer.listenOn(serverSocket);
setState(() {
statusText = "Server running on IP : "+server.address.toString()+" On Port : "+server.port.toString();
});
print("Server running on IP : "+server.address.toString()+" On Port : "+server.port.toString());
await for (var request in server) {
setState(() {
statusText = request.requestedUri.toString();
});
request.response.headers.contentType = new ContentType("text", "plain", charset: "utf-8");
request.response.write("hello world");
request.response.close();
print("Response served\n");
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: (){startServer();},
child: Text(statusText),)],),));
}
}
Testing on
Ubuntu 16.04 lts
Tested with and without firewall
Need this to host a web service
Any other methods available within Flutter are welcome
Haven't yet tried with threading
First, dart:io are not supported in web browsers so that explain your problem with running the code in browsers:
Important: Browser-based applications can't use this library. Only servers, command-line scripts, and Flutter mobile apps can import and use dart:io.
https://api.dart.dev/stable/2.8.4/dart-io/dart-io-library.html
Second, your code is very complicated if the purpose is to create a simple HTTP server running on a headless server. I have simplified your code so it does no longer depend on Flutter and can just be executed with dart:
import 'dart:io';
void main() {
startServer();
}
Future<void> startServer() async {
print("Starting server on Port : 8088");
print("Attempting bind");
final server = await HttpServer.bind("0.0.0.0", 8080);
print("Server running on IP : ${server.address} On Port : ${server.port}");
await for (final request in server) {
print(request.requestedUri);
request.response
..headers.contentType = ContentType("text", "plain", charset: "utf-8")
..write("hello world");
await request.response.flush();
await request.response.close();
print("Response served\n");
}
}
Related
I'm using Flutter web and strapi headless cms for backend. I'm able to send the files successfully, but would like its progress indication. Backend restrictions: File upload must be multipart form-data, being it a buffer or stream. Frontend restrictions: Flutter web doesn't have access to system file directories; files must be loaded in memory and sent using its bytes.
I'm able to upload the file using flutter's http package or the Dio package, but have the following problems when trying to somehow access upload progress:
Http example code:
http.StreamedResponse response;
final uri = Uri.parse(url);
final request = MultipartRequest(
'POST',
uri,
);
request.headers['authorization'] = 'Bearer $_token';
request.files.add(http.MultipartFile.fromBytes(
'files',
_fileToUpload.bytes,
filename: _fileToUpload.name,
));
response = await request.send();
var resStream = await response.stream.bytesToString();
var resData = json.decode(resStream);
What I tryed:
When acessing the response.stream for the onData, it only responds when the server sends the finished request (even though the methods states it's supposed to gets some indications of progress).
Dio package code
Response response = await dio.post(url,
data: formData,
options: Options(
headers: {
'authorization': 'Bearer $_token',
},
), onSendProgress: (int sent, int total) {
setState(() {
pm.progress = (sent / total) * 100;
});
The problems:
It seems the package is able to get some progress indication, but Dio package for flutter web has a bug which has not been fixed: requests block the ui and the app freezes until upload is finished.
Hi you can use the universal_html/html.dart package to do the progress bar, here are steps:
to import universal package
import 'package:universal_html/html.dart' as html;
Select files from html input element instead using file picker packages
_selectFile() {
html.FileUploadInputElement uploadInput = html.FileUploadInputElement();
uploadInput.multiple = false;
uploadInput.accept = '.png,.jpg,.glb';
uploadInput.click();
uploadInput.onChange.listen((e) {
_file = uploadInput.files.first;
});
}
Create upload_worker.js into web folder, my example is upload into S3 post presigned url
self.addEventListener('message', async (event) => {
var file = event.data.file;
var url = event.data.uri;
var postData = event.data.postData;
uploadFile(file, url, postData);
});
function uploadFile(file, url, presignedPostData) {
var xhr = new XMLHttpRequest();
var formData = new FormData();
// if you use postdata, you can open the comment
//Object.keys(presignedPostData).forEach((key) => {
// formData.append(key, presignedPostData[key]);
//});
formData.append('Content-Type', file.type);
// var uploadPercent;
formData.append('file', file);
xhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
console.log(e.loaded + "/" + e.total);
// pass progress bar status to flutter widget
postMessage(e.loaded/e.total);
}
});
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
// postMessage("done");
}
}
xhr.onerror = function () {
console.log('Request failed');
// only triggers if the request couldn't be made at all
// postMessage("Request failed");
};
xhr.open('POST', url, true);
xhr.send(formData);
}
Flutter web call upload worker to upload and listener progress bar status
class Upload extends StatefulWidget {
#override
_UploadState createState() => _UploadState();
}
class _UploadState extends State<Upload> {
html.Worker myWorker;
html.File file;
_uploadFile() async {
String _uri = "/upload";
final postData = {};
myWorker.postMessage({"file": file, "uri": _uri, "postData": postData});
}
_selectFile() {
html.InputElement uploadInput = html.FileUploadInputElement();
uploadInput.multiple = false;
uploadInput.click();
uploadInput.onChange.listen((e) {
file = uploadInput.files.first;
});
}
#override
void initState() {
myWorker = new html.Worker('upload_worker.js');
myWorker.onMessage.listen((e) {
setState(() {
//progressbar,...
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
children: [
RaisedButton(
onPressed: _selectFile,
child: Text("Select File"),
),
RaisedButton(
onPressed: _uploadFile,
child: Text("Upload"),
),
],
);
}
}
that's it, I hope it can help you.
I'm trying to serve local content from assets through https, in order to gain access to features like webrtc which require ssl.
Since the local app server provided in flutter_inappwebview
does not handle ssl connections, I've replaced the InAppLocalHostServer class with InAppLocalHostSecureServer with the following code:
import 'dart:io';
import 'dart:async';
import 'package:flutter/services.dart' show rootBundle;
import 'package:mime/mime.dart';
class InAppLocalHostSecureServer {
HttpServer _server;
int _port = 8443;
InAppLocalHostSecureServer({int port = 8443}) {
this._port = port;
}
///Starts a server on http://localhost:[port]/.
///
///**NOTE for iOS**: For the iOS Platform, you need to add the `NSAllowsLocalNetworking` key with `true` in the `Info.plist` file (See [ATS Configuration Basics](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW35)):
///```xml
///<key>NSAppTransportSecurity</key>
///<dict>
/// <key>NSAllowsLocalNetworking</key>
/// <true/>
///</dict>
///```
///The `NSAllowsLocalNetworking` key is available since **iOS 10**.
Future<void> start() async {
if (this._server != null) {
throw Exception('Server already started on https://localhost:$_port');
}
var completer = Completer();
runZoned(() async {
SecurityContext context = new SecurityContext();
var chain = await rootBundle.load('assets/certificates/cert.pem');
var key = await rootBundle.load('assets/certificates/key.pem');
context.useCertificateChainBytes(chain.buffer.asInt8List());
context.usePrivateKeyBytes(key.buffer.asInt8List(), password: 'dartdart');
HttpServer.bindSecure('127.0.0.1', _port, context).then((server) {
print('Server running on https://localhost:' + _port.toString());
this._server = server;
server.listen((HttpRequest request) async {
print(request);
var body = List<int>();
var path = request.requestedUri.path;
path = (path.startsWith('/')) ? path.substring(1) : path;
path += (path.endsWith('/')) ? 'index.html' : '';
try {
body = (await rootBundle.load(path)).buffer.asUint8List();
} catch (e) {
print(e.toString());
request.response.close();
return;
}
var contentType = ['text', 'html'];
if (!request.requestedUri.path.endsWith('/') &&
request.requestedUri.pathSegments.isNotEmpty) {
var mimeType =
lookupMimeType(request.requestedUri.path, headerBytes: body);
if (mimeType != null) {
contentType = mimeType.split('/');
}
}
request.response.headers.contentType =
ContentType(contentType[0], contentType[1], charset: 'utf-8');
request.response.add(body);
request.response.close();
});
completer.complete();
});
}, onError: (e, stackTrace) {
print('Error: $e $stackTrace');
});
return completer.future;
}
///Closes the server.
Future<void> close() async {
if (this._server != null) {
await this._server.close(force: true);
print('Server running on http://localhost:$_port closed');
this._server = null;
}
}
}
Most of the code is a copy paste of the original class.
What I changed is that I call HttpServer.bindSecure instead of HttpServer.bind and I provide openssl certificate and key.
The server seems to start without error logged in the console, but I cannot access it.
Here is the client code that try to access a local url:
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'InAppLocalHostSecureServer.dart';
class WebAudioTest extends StatefulWidget {
#override
_WebAudioTestState createState() => _WebAudioTestState();
}
class _WebAudioTestState extends State<WebAudioTest> {
InAppWebViewController webView;
InAppLocalHostSecureServer localhostServer;
String url = "https://127.0.0.1:8443/assets/web/index.html";
#override
void initState() {
super.initState();
this.init();
}
void init() async {
this.localhostServer = new InAppLocalHostSecureServer();
await localhostServer.start();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Web Audio Test'),
),
body: InAppWebView(
initialUrl: url,
initialHeaders: {},
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
debuggingEnabled: true,
)),
onWebViewCreated: (InAppWebViewController c) {
webView = c;
},
onConsoleMessage: (controller, consoleMessage) {
print("CONSOLE MESSAGE: " + consoleMessage.message);
},
),
);
}
}
No error appears in the console but the flutter page display the following error message:
net::ERR_CONNECTION_REFUSED
Any help is welcome.
Ok, to answer my own questions:
the problem I had was simply that I build the InAppWebView too early, before the server has finished to launch. The solution is easy, just set a flag to true when the server is launched, and create the InAppWebView only when the flag is true.
Beside this, WebRTC works without https on localhost, I tested it on Android and iOS. So no need for local https for this use case.
But anyway if for any other reason someone needs to to serve https local content, the code in this post can serve as a basis for this.
I have created a server using a Plane dart and trying to listen to the response using HTTP get. I can access the response when I ping the I/P in browser but when trying to access in a demo app i get the error
SocketException: OS Error: Connection refused, errno = 111, address = 127.0.0.1, port = 36000
My Server code is as below :
class ServerUtilities {
static Directory _appDirectory;
static HttpServer _server;
static File _file;
ServerUtilities._();
static ServerUtilities _obj;
static ServerUtilities instance() {
if (_obj == null) _obj = ServerUtilities._();
return _obj;
}
Future<Directory> setAppDirectory() async {
return await getApplicationDocumentsDirectory();
}
void initializeServer(String address, int port) async {
_appDirectory = await setAppDirectory();
print(_appDirectory.path);
_file = File('${_appDirectory.path}/sample.txt');
_file.writeAsString("Hiii ", mode: FileMode.append);
_server = await HttpServer.bind(address, port);
print("Server initialized - " + address + ":" + port.toString());
await for (var req in _server) {
if (await _file.exists()) {
print("file exist");
// req.response.headers.contentType = ContentType.text;
await _file.openRead().pipe(req.response);
}
}
}
void stopServer() async {
await _server.close().catchError(
(e) {
print(e);
},
).then(
(value) => {
print("Server stopped "),
},
);
}
}
The server got initialized and everything works fine and can open the provided IP in my mobile browser and it works well but when trying to use Http.get i got the above error.
This is my main.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
ServerUtilities.instance().initializeServer('127.0.0.1', 8010);
runApp(
MaterialApp(
home: MyApp(),
),
);
}
And this is how I am trying to access, And I am getting the above-specified error.
FutureBuilder(
future: http.get("http://127.0.0.1:8010"),
builder: (context, data) {
if (data.hasData)
return Text(
data.toString(),
style: TextStyle(fontSize: 20),
);
else if (data.hasError) {
print(data.error);
return Text(
data.error.toString(),
style: TextStyle(fontSize: 20),
);
} else
return Text(
"No data",
style: TextStyle(fontSize: 20),
);
}),
This error comes when the Server is not running. So please check whether initializeServer method is working correctly or not.
Programmatically generated dynamic links are not properly catched by
FirebaseDynamicLinks.instance.getInitialLink().
if the app is closed. However, if the app is open it is properly detected by the listener for new incoming dynamic links. It is not clear to me if it is a setup problem, how I generate the dynamic link.
To Reproduce
First set up Firebase for Flutter project as documented. Then to set up a dynamic link:
/// See also
/// https://firebase.google.com/docs/dynamic-links/use-cases/rewarded-referral
/// how to implement referral schemes using Firebase.
Future<ShortDynamicLink> buildDynamicLink(String userId) async {
final PackageInfo packageInfo = await PackageInfo.fromPlatform();
final String packageName = packageInfo.packageName;
var androidParams = AndroidParameters(
packageName: packageInfo.packageName,
minimumVersion: Constants.androidVersion, // app version and not the Android OS version
);
var iosParams = IosParameters(
bundleId: packageInfo.packageName,
minimumVersion: Constants.iosVersion, // app version and not the iOS version
appStoreId: Constants.iosAppStoreId,
);
var socialMetaTagParams = SocialMetaTagParameters(
title: 'Referral Link',
description: 'Referred app signup',
);
var dynamicLinkParams = DynamicLinkParameters(
uriPrefix: 'https://xxxxxx.page.link',
link: Uri.parse('https://www.xxxxxxxxx${Constants.referralLinkPath}?${Constants.referralLinkParam}=$userId'),
androidParameters: androidParams,
iosParameters: iosParams,
socialMetaTagParameters: socialMetaTagParams,
);
return dynamicLinkParams.buildShortLink();
}
This dynamic link then can be shared with other new users.
I listen for initial links at app startup and then for new incoming links.
1) The link properly opens the app if the app is not running but the getInitialLink does not get it.
2) If the app is open the link is properly caught by the listener and all works.
Here is the very simple main.dart that I used to verify 1) that the initial link is not found with FirebaseDynamicLinks.instance.getInitialLink().
void main() async {
WidgetsFlutterBinding.ensureInitialized();
PendingDynamicLinkData linkData = await FirebaseDynamicLinks.instance.getInitialLink();
String link = linkData?.link.toString();
runApp(MyTestApp(link: link));
}
class MyTestApp extends StatelessWidget {
final String link;
MyTestApp({this.link});
#override
Widget build(BuildContext context) {
return MaterialApp(
builder: (BuildContext context, Widget child) {
return Scaffold(
body: Container(
child: Center(
child: Text('Initial dynamic Firebase link: $link')
),
),
);
}
);
}
}
Expected behavior
The link should open the app and trigger FirebaseDynamicLinks.instance.getInitialLink()..
Additional context
I hope properly configured Firebase project with Firebase console. To verify this I created a dynamic link to be used with Firebase Auth 'signup by email link' and these dynamic links are working as expected, also when the app is not open.
The point here is that the referral dynamic link that I generate programmatically is opening the app when it is closed but is then not caught by FirebaseDynamicLinks.instance.getInitialLink(), and to make things more confusing, works as expected if the app is open. In that case it is caught by the listener FirebaseDynamicLinks.instance.onLink.
I also set up the WidgetsBindingObserver in Flutter to handle that callback as required, when the app gets its focus back.
Any help is greatly appreciated. Debugging is very tricky, as you need to do it on a real device and not in the simulator. To make things worse, I did not figure out how to attach a debugger while the dynamic link opens the app. This means I am also stuck in investigating this issue further.
In The FirebaseDynamicLinks Two Methods 1) getInitialLink() 2) onLink().
If When Your App Is Open And You Click On Dynamic Link Then Will Be Call FirebaseDynamicLinks.instance.onLink(), If Your App Is Killed Or Open From PlayStore Then You Get From FirebaseDynamicLinks.instance.getInitialLink();.
First Of You Need To Initialise Instance Of FirebaseDynamicLinks.instance.
static void initDynamicLinks() async {
final PendingDynamicLinkData data =
await FirebaseDynamicLinks.instance.getInitialLink();
final Uri deepLink = data?.link;
if (deepLink != null && deepLink.queryParameters != null) {
SharedPrefs.setValue("param", deepLink.queryParameters["param"]);
}
FirebaseDynamicLinks.instance.onLink(
onSuccess: (PendingDynamicLinkData dynamicLink) async {
final Uri deepLink = dynamicLink?.link;
if (deepLink != null && deepLink.queryParameters != null) {
SharedPrefs.setValue("param", deepLink.queryParameters["param]);
}
}, onError: (OnLinkErrorException e) async {
print(e.message);
});
}
Initialize Link Listener. This works for me.
class _MainAppState extends State<MainApp> {
Future<void> initDynamicLinks() async {
print("Initial DynamicLinks");
FirebaseDynamicLinks dynamicLinks = FirebaseDynamicLinks.instance;
// Incoming Links Listener
dynamicLinks.onLink.listen((dynamicLinkData) {
final Uri uri = dynamicLinkData.link;
final queryParams = uri.queryParameters;
if (queryParams.isNotEmpty) {
print("Incoming Link :" + uri.toString());
// your code here
} else {
print("No Current Links");
// your code here
}
});
// Search for Firebase Dynamic Links
PendingDynamicLinkData? data = await dynamicLinks
.getDynamicLink(Uri.parse("https://yousite.page.link/refcode"));
final Uri uri = data!.link;
if (uri != null) {
print("Found The Searched Link: " + uri.toString());
// your code here
} else {
print("Search Link Not Found");
// your code here
}
}
Future<void> initFirebase() async {
print("Initial Firebase");
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// await Future.delayed(Duration(seconds: 3));
initDynamicLinks();
}
#override
initState() {
print("INITSTATE to INITIALIZE FIREBASE");
super.initState();
initFirebase();
}
I tried Rohit's answer and because several people face the same issue I add here some more details. I created a stateful widget that I place pretty much at the top of the widget tree just under material app:
class DynamicLinkWidget extends StatefulWidget {
final Widget child;
DynamicLinkWidget({this.child});
#override
State<StatefulWidget> createState() => DynamicLinkWidgetState();
}
class DynamicLinkWidgetState extends State<DynamicLinkWidget> with WidgetsBindingObserver {
#override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
locator.get<DynamicLinkService>().initDynamicLinks();
}
#override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
#override
Widget build(BuildContext context) {
return Container(child: widget.child);
}
}
I use the getit package to inject services. The dynamic link service is roughly like this:
class DynamicLinkService {
final UserDataService userDataService;
final ValueNotifier<bool> isLoading = ValueNotifier<bool>(false);
final BehaviorSubject<DynamicLinkError> _errorController = BehaviorSubject<DynamicLinkError>();
Stream<DynamicLinkError> get errorStream => _errorController.stream;
DynamicLinkService({#required this.userDataService});
void initDynamicLinks() async {
final PendingDynamicLinkData data = await FirebaseDynamicLinks.instance.getInitialLink();
final Uri deepLink = data?.link;
if (deepLink != null) {
processDynamicLink(deepLink);
}
FirebaseDynamicLinks.instance.onLink(
onSuccess: (PendingDynamicLinkData dynamicLink) async {
final Uri deepLink = dynamicLink?.link;
if (deepLink != null) {
print('=====> incoming deep link: <${deepLink.toString()}>');
processDynamicLink(deepLink);
}
},
onError: (OnLinkErrorException error) async {
throw PlatformException(
code: error.code,
message: error.message,
details: error.details,
);
}
);
}
Future<void> processDynamicLink(Uri deepLink) async {
if (deepLink.path == Constants.referralLinkPath && deepLink.queryParameters.containsKey(Constants.referrerLinkParam)) {
var referrer = referrerFromDynamicLink(deepLink);
userDataService.processReferrer(referrer);
} else {
await FirebaseEmailSignIn.processDynamicLink(
deepLink: deepLink,
isLoading: isLoading,
onError: this.onError
);
}
}
void onError(DynamicLinkError error) {
_errorController.add(error);
}
}
You see that my app has to process two types of dynamic link, one is for email link signup, the other link is our referral link that is used to link users together and allow us to understand who introduced a new user to us. This setup works now for us. Hope it helps others too.
I am trying to take a picture with my Android camera, upload that picture to Google Firebase Storage, get the downloadable URL of that image on Storage, and update the user's photo feed on Firestore. If I only call takeImage() it takes the image and uploads successfully to storage. If I call _uploadImage with a dummy image url, it correctly updates the feed. But I cannot get the result of takeImage to pass as a parameter to _uploadImage().
void takeAndSave() async {
url = await takeImage();
_uploadImage(url);
}
Future<String> takeImage() async {
// open camera
var image = await ImagePicker.pickImage(source: ImageSource.camera);
// save image to temp storage
final String fileName = "${Random().nextInt(10000)}.jpg";
Directory directory = await getApplicationDocumentsDirectory(); // AppData folder path
String appDocPath = directory.path;
// copy image to path
File savedImage = await image.copy('$appDocPath/' + fileName);
// upload file to Firebase Storage
final StorageReference ref = FirebaseStorage.instance.ref().child(fileName);
final StorageUploadTask task = ref.putFile(savedImage);
String downloadURL = await ref.getDownloadURL();
url = downloadURL;
// _image = image;
return downloadURL;
}
Future<void> _uploadImage(String url) async {
final FirebaseUser user = await widget.auth.currentUser();
String uid = user.uid;
print('uid = ' + uid);
print(url);
// upload URL to Firebase Firestore Cloud Storage
Firestore.instance.runTransaction((Transaction transaction) async {
DocumentReference _newPhoto = Firestore.instance.collection('users').document(user.uid);
await _newPhoto.collection('cards').add({"url" : url});
});
}
To chain future tasks: means if we have two future tasks and second is dependent upon result of first response then we can use "Future.wait()". In the below example i have created two methods with async keyword that will fetch data from server and i want to execute "fetchPostAgain()" method after the response of first "fetchPost()" then i can use "Future.wait()".
import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_app/models/Post.dart';
import 'package:http/http.dart' as http;
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
void initState() {
super.initState();
}
FetchFirstPost getFirstPost;
String myString = "Loading...";
void _takeImage() {
Future.wait([fetchPost()]).then((FutureOr) => {
fetchPostAgain()
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Example'),
),
body: Center(
child: Column(
children: <Widget>[
SingleChildScrollView(
child: Text(myString),
),
RaisedButton(
child: Text("Run Future"),
onPressed: _takeImage,
),
],
),
/*child: CallApiDemo(),*/
),
),
);
}
Future<Post> fetchPost() async {
final Completer completer = Completer();
final response = await http.get('https://jsonplaceholder.typicode.com/posts/1');
log('data: ' + response .statusCode.toString());
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
setState(() {
myString = response.body;
});
return postFromJson(response.body);
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
Future<Post> fetchPostAgain() async{
final response = await http.get('https://jsonplaceholder.typicode.com/posts/1');
log('GOT SECOND RESPONSE');
log('data: ' + response .statusCode.toString());
if (response.statusCode == 200) {
setState(() {
myString = myString + "\n\n\nAGAIN\n\n\n" + response.body;
});
return postFromJson(response.body);
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
}
As per your code, it should work properly, but there could be a chance that your takeImage() method is returning an exception. Try catching that exception and see if it helps.
Below is referenced from https://www.dartlang.org/tutorials/language/futures#async-await
If a Future-returning function completes with an error, you probably want to capture that error. Async functions can handle errors using try-catch:
Future<String> takeImage() async {
try {
// Your code
} catch (e) {
// Handle error...
}
}