I am learning Flutter and Dart currently. Now I want to read and write files to memory. I have code for reading and writing. Now I want tests for that. Here is where I run into problems. I always get:
'package:flutter/src/services/platform_channel.dart': Failed assertion: line 134 pos 7: '_binaryMessenger != null || ServicesBinding.instance != null': Cannot use this MethodChannel before the binary messenger has been initialized. This happens when you invoke platform methods before the WidgetsFlutterBinding has been initialized. You can fix this by either calling WidgetsFlutterBinding.ensureInitialized() before this or by passing a custom BinaryMessenger instance to MethodChannel().
dart:core _AssertionError._throwNew
package:flutter/src/services/platform_channel.dart 134:7 MethodChannel.binaryMessenger
package:flutter/src/services/platform_channel.dart 167:36 MethodChannel._invokeMethod
package:flutter/src/services/platform_channel.dart 350:12 MethodChannel.invokeMethod
package:path_provider_macos/path_provider_macos.dart 48:10 PathProviderMacOS.getApplicationDocumentsPath
package:path_provider/path_provider.dart 115:40 getApplicationDocumentsDirectory
package:skeet25pro/main_counter.dart 18:29 CounterStorage._localPath
package:skeet25pro/main_counter.dart 24:24 CounterStorage._localFile
package:skeet25pro/main_counter.dart 43:24 CounterStorage.writeCounter
test/file_io_test.dart 8:27 main.<fn>
test/file_io_test.dart 5:33 main.<fn>
main_counter.dart
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(
MaterialApp(
title: 'Reading and Writing Files',
home: FlutterDemo(storage: CounterStorage()),
),
);
}
class CounterStorage {
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}
Future<int> readCounter() async {
try {
final file = await _localFile;
// Read the file
final contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If encountering an error, return 0
return 0;
}
}
Future<File> writeCounter(int counter) async {
final file = await _localFile;
// Write the file
return file.writeAsString('$counter');
}
}
class FlutterDemo extends StatefulWidget {
const FlutterDemo({Key? key, required this.storage}) : super(key: key);
final CounterStorage storage;
#override
_FlutterDemoState createState() => _FlutterDemoState();
}
class _FlutterDemoState extends State<FlutterDemo> {
int _counter = 0;
#override
void initState() {
super.initState();
widget.storage.readCounter().then((int value) {
setState(() {
_counter = value;
});
});
}
Future<File> _incrementCounter() {
setState(() {
_counter++;
});
// Write the variable as a string to the file.
return widget.storage.writeCounter(_counter);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Reading and Writing Files'),
),
body: Center(
child: Text(
'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
file_io_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:skeet25pro/main_counter.dart';
void main() {
test('Check file save works', () async {
final CounterStorage storage = CounterStorage();
var counter = 6;
var t = await storage.writeCounter(counter);
expect(1, 1);
});
}
When I run the app through a simulator, it works perfectly fine. I would really like to get the tests running.
EDIT: If I try and add WidgetsFlutterBinding.ensureInitialized();
void main() {
test('Check file save works', () async {
WidgetsFlutterBinding.ensureInitialized();
final CounterStorage storage = CounterStorage();
var counter = 6;
var t = await storage.writeCounter(counter);
expect(1, 1);
});
}
I get the error:
MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider_macos)
package:flutter/src/services/platform_channel.dart 175:7 MethodChannel._invokeMethod
Seems like one should use something like: setMockMethodCallHandler to intercept the call to the different directory providers. Still no working solution.
You have to mock the path_provider call and maybe put the WidgetsFlutterBinding.ensureInitialized(); at the beginning of main. I guess you want something like
Future<void> main() async {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() {
const channel = MethodChannel(
'plugins.flutter.io/path_provider_macos',
);
channel.setMockMethodCallHandler((MethodCall methodCall) async {
switch (methodCall.method) {
case 'getApplicationDocumentsDirectory':
return "PATH_TO_MOCK_DIR";
default:
}
});
});
test('Check file save works', () async {
final CounterStorage storage = CounterStorage();
var counter = 6;
var t = await storage.writeCounter(counter);
expect(1, 1);
});
}```
Related
I am trying to import starflut package in flutter but i am getting a lot of exceptions which i am not able to solve.I have copy pasted the file according to (https://github.com/srplab/starcore_for_flutter).
Use this line to run the code in terminal :flutter run --no-sound-null-safety
enter image description here
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:starflut/starflut.dart';
import 'dart:async';
import 'package:flutter/services.dart';
void main() {
runApp(MaterialApp(home: const MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(
onTap: () async {
await initpla();
},
child: Container(
width: 350,
height: 500,
color: Colors.blue,
),
),
);
}
Future<void> initpla() async {
try {
StarCoreFactory starcore = await Starflut.getFactory();
StarServiceClass Service =
await starcore.initSimple("test", "123", 0, 0, []);
await starcore.regMsgCallBackP(
(int serviceGroupID, int uMsg, Object wParam, Object lParam) async {
print("$serviceGroupID $uMsg $wParam $lParam");
return null;
});
dynamic SrvGroup = await Service["_ServiceGroup"];
bool isAndroid = await Starflut.isAndroid();
if (isAndroid == true) {
//desRelatePath must be null
await Starflut.loadLibrary("libpython3.9.so");
await Starflut.copyFileFromAssets(
"python3.9.zip", "flutter_assets/starflut", null);
var nativepath = await Starflut.getNativeLibraryDir();
print("Nativepath : $nativepath");
var LibraryPath = "";
if (nativepath.contains("x86_64"))
LibraryPath = "x86_64";
else if (nativepath.contains("arm64"))
LibraryPath = "arm64";
else if (nativepath.contains("arm"))
LibraryPath = "armeabi";
else if (nativepath.contains("x86")) LibraryPath = "x86";
await Starflut.copyFileFromAssets(
"zlib.cpython-39.so", LibraryPath, null);
await Starflut.copyFileFromAssets(
"unicodedata.cpython-39.so", LibraryPath, null);
String docPath = await Starflut.getDocumentPath();
print("docPath = $docPath");
String resPath = await Starflut.getResourcePath();
print("resPath = $resPath");
dynamic rr1 = await SrvGroup.initRaw("python39", Service);
var Result = await SrvGroup.loadRawModule(
"python", "", resPath + "/" + "abc.py", false);
print("loadRawModulee = $Result");
dynamic python =
await Service.importRawContext(null, "python", "", false, "");
await SrvGroup.clearService();
await starcore.moduleExit();
String platformVersion = 'Python 3.9';
}
} catch (e) {
print("{$e.message}");
}
}
}
Please i need some help and thanks in advance.
I am reciving over Websocket a Json that i want to safe locally.
But before saving it, i am trying to compare the recieved Json with the existend locad Json. If the value of count_json does not exist inside the local file it would need to save the Json to a new line and if the value of count_json would already exist it would do nothing.
At this moment, i am able to save it localy, and write it down to a new line in the file.
But i have two problems that i do not know how to solve it.
How i am making the comparising is not good. Because it is saving the recieved Json to a new line even the value of count_jsonalready exist, like as follow.
{"count_json":1,"range_json":[5.5,8.9,7.5,6.7,8.7],"force_json":[5.4,5.3,5.2,5.2,5.1]}
{"count_json":1,"range_json":[9.5,8.3,12.4,13.1,8.5],"force_json":[4.9,4.8,4.8,4.9,5]}
{"count_json":1,"range_json":[11.7,9.7,9.9,11.8,10.2],"force_json":[4.9,5,5.2,5.3,5.5]}
{"count_json":2,"range_json":[19.6,19.6,19.6,19.6,19.6],"force_json":[10,10,10,10,10]}
{"count_json":2,"range_json":[19.4,19.6,19.6,19.6,19.6],"force_json":[9.9,10,10,10,10]}
{"count_json":2,"range_json":[19.4,19.6,19.6,19.6,19.6],"force_json":[9.9,10,10,10,10]}
{"count_json":2,"range_json":[19.4,19.7,19.6,19.6,19.6],"force_json":[9.9,10,10,10,10]}
.
.
But i am expenting this
{"count_json":1,"range_json":[5.5,8.9,7.5,6.7,8.7],"force_json":[5.4,5.3,5.2,5.2,5.1]}
{"count_json":2,"range_json":[19.4,19.7,19.6,19.6,19.6],"force_json":[9.9,10,10,10,10]}
.
.
My approach on how to compara and safe is as follow.
Map<String, dynamic> jsondat = json.decode(message);
String data = json.encode(jsondat);
setState(() {
if (data.contains("count_json")) {
istcycles = jsondat['count_json']; //cycles value
connectedS1Status = true;
if (_myjson['count_json'] != 0) {
_filePath.writeAsString('$data\n', mode: FileMode.append);
}
}
});
If i open the local Json file in Visual Studio code it give me the error message
End of file Expected
That means the stuctur of how i a writing and saving to the Json file is not properly. See above how the structure is inside the file.
Follow the complete code.
//https://docs.flutter.dev/cookbook/persistence/reading-writing-files
// ignore_for_file: avoid_print
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:web_socket_channel/io.dart';
import 'dart:io';
import 'dart:async';
const String fileName = 'myJsonFile.json';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(home: HomePage());
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
// ignore: library_private_types_in_public_api
_HomePageState createState() {
return _HomePageState();
}
}
class _HomePageState extends State<HomePage> {
late IOWebSocketChannel channel;
late bool
connectedS1Status; //boolean value to track if WebSocket is connected
late int istcycles; //variable for istcycles
late double istforcesensor;
late double istrangesensor;
#override
void initState() {
connectedS1Status =
false; //initially connection status is "NO" so its FALSE
Future.delayed(Duration.zero, () async {
channelconnect(); //connect to WebSocket wth NodeMCU
});
// Instantiate _controllerKey and _controllerValue
print('0. Initialized _myjson: $_myjson');
_readJson();
istcycles = 0; //initial value of istcycles
istforcesensor = 0;
istrangesensor = 0;
super.initState();
}
channelconnect() {
try {
channel = IOWebSocketChannel.connect(
"ws://192.168.1.100:80"); //channel IP : Port
channel.stream.listen(
(message) {
//print(message);
Map<String, dynamic> jsondat = json.decode(message);
String data = json.encode(jsondat);
setState(() {
if (data.contains("count_json")) {
istcycles = jsondat['count_json']; //cycles value
connectedS1Status = true;
if (_myjson['count_json'] != 0) {
_filePath.writeAsString('$data\n', mode: FileMode.append);
}
}
});
},
onDone: () {
print("Web socket is closed");
setState(() {
connectedS1Status = false;
});
},
onError: (error) {
print(error.toString());
},
);
} catch (_) {
print("error on connecting to websocket.");
}
}
bool _fileExists = false;
late File _filePath;
// First initialization of _json (if there is no json in the file)
late Map<String, dynamic> _myjson = {};
late String _myjsonString;
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/$fileName');
}
//------------------------------------------------------------------------------------
// _readJson--------------------------------------------------------------------------
//------------------------------------------------------------------------------------
void _readJson() async {
// Initialize _filePath
_filePath = await _localFile;
// 0. Check whether the _file exists
_fileExists = await _filePath.exists();
print('0. File exists? $_fileExists');
// If the _file exists->read it: update initialized _json by what's in the _file
if (_fileExists) {
try {
//1. Read _jsonString<String> from the _file.
_myjsonString = await _filePath.readAsString();
print('1.(_readJson) _jsonString: $_myjsonString');
//2. Update initialized _json by converting _jsonString<String>->_json<Map>
_myjson = jsonDecode(_myjsonString);
print('2.(_readJson) _json: $_myjson \n - \n');
} catch (e) {
// Print exception errors
print('Tried reading _file error: $e');
// If encountering an error, return null
}
}
}
#override
void dispose() {
super.dispose();
}
// Delete Function-------------------------------------------
Future<int> deleteFile() async {
try {
final file = await _localFile;
await file.delete();
} catch (e) {
return 0;
}
return 0;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("WebSocket Json"),
backgroundColor: Colors.redAccent),
body: Container(
alignment: Alignment.topCenter, //inner widget alignment to center
padding: const EdgeInsets.all(20),
child: Column(
children: [
Container(
//showing if websocket is connected or disconnected
child: connectedS1Status
? const Text("WEBSOCKET: CONNECTED")
: const Text("DISCONNECTED")),
Text("Cycles: $istcycles "),
],
)),
);
}
}
I'm trying to use flutter_downloader package to download some files (images/pdf). There is a listView with ListTiles each containing a button to start downloading when clicked but this error occurs when scrolling the list view.
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: 'package:flutter_downloader/src/downloader.dart': Failed assertion: line 30 pos 12: '!_initialized': FlutterDownloader.initialize() must be called only once!
//my code is like this:
import 'dart:io';
import 'dart:isolate';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
class DownloadFile extends StatefulWidget {
DownloadFile({this.downloadUrl});
final String downloadUrl;
#override
_DownloadFileState createState() => _DownloadFileState();
}
class _DownloadFileState extends State<DownloadFile> {
String downloadId;
String _localPath;
ReceivePort _port = ReceivePort();
#override
void initState(){
super.initState();
_init();
}
Future<void> _init() async {
await FlutterDownloader.initialize();
IsolateNameServer.registerPortWithName(
_port.sendPort, 'downloader_send_port');
_port.listen((dynamic data) {
String id = data[0];
DownloadTaskStatus status = data[1];
int progress = data[2];
print("status: $status");
print("progress: $progress");
print("id == downloadId: ${id == downloadId}");
});
FlutterDownloader.registerCallback(downloadCallback);
_localPath = (await _findLocalPath()) + '/Download';
final savedDir = Directory(_localPath);
bool hasExisted = await savedDir.exists();
if (!hasExisted) {
savedDir.create();
}
}
static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
print(
'Background Isolate Callback: task ($id) is in status ($status) and process ($progress)');
final SendPort send =
IsolateNameServer.lookupPortByName('downloader_send_port');
send.send([id, status, progress]);
}
Future<String> _findLocalPath() async {
final directory = await getExternalStorageDirectory();
return directory.path;
}
Future<bool> _checkPermission() async {
if (Theme.of(context).platform == TargetPlatform.android) {
PermissionStatus permission = await PermissionHandler()
.checkPermissionStatus(PermissionGroup.storage);
if (permission != PermissionStatus.granted) {
Map<PermissionGroup, PermissionStatus> permissions =
await PermissionHandler()
.requestPermissions([PermissionGroup.storage]);
if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
return true;
}
} else {
return true;
}
} else {
return true;
}
return false;
}
//----------------------------------------------------------------
#override
void dispose() {
super.dispose();
}
//---------------------------------------------------------------
#override
Widget build(BuildContext context) {
return FlatButton(
onPressed: () async {
if (await _checkPermission()) {
final taskId = await FlutterDownloader.enqueue(
url: widget.downloadUrl,
savedDir: _localPath,
showNotification:
true, // show download progress in status bar (for Android)
openFileFromNotification:
true, // click on notification to open downloaded file (for Android)
);
downloadId = taskId;
}
},
child: Text('Downloa File',style: TextStyle(color: Colors.teal),)
);
}
}
According to the Usage section in the flutter_downloader package and the error you are getting, you must call the FlutterDownloader.initialize not more than once.
You can do that in the main method of your application, just like so:
WidgetsFlutterBinding.ensureInitialized();
await FlutterDownloader.initialize();
I am trying to write the code for signing out of a flutter app logging in (The database of the map is made with sqflite).
However I am getting the following error message:
flutter: NoSuchMethodError: The method 'notify' was called on null.
Receiver: null
Tried calling: notify(Instance of 'AuthState')
Have provided code of required files below.
I am trying to incorporate a sign out function in the home_screen.dart file but I feel I am missing a link between the auth.dart, auth_provider.dart, login_screen.dart and home_screen.dart files. The codes of the required files for the issue are as follows:
File: database_helper.dart
import 'dart:async';
import 'dart:io' as io;
import 'package:path/path.dart';
import 'package:better_login/user.dart';
import 'package:sqflite/sqflite.dart' ;
import 'package:path_provider/path_provider.dart';
class DatabaseHelper {
static final DatabaseHelper _instance = new
DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database _db;
Future<Database> get db async {
if(_db != null)
return _db;
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async {
io.Directory documentsDirectory = await
getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "main.db");
var theDb = await openDatabase(path, version: 1, onCreate:
_onCreate);
return theDb;
}
void _onCreate(Database db, int version) async {
// When creating the db, create the table
await db.execute(
"CREATE TABLE User(username TEXT,password TEXT)");
print("Created tables");
}
Future<int> saveUser(User user) async {
var dbClient = await db;
int res = await dbClient.insert("User", user.toMap());
return res;
}
Future<int> deleteUsers() async {
var dbClient = await db;
int res = await dbClient.delete("User");
return res;
}
Future<bool> isLoggedIn() async {
var dbClient = await db;
var res = await dbClient.query("User");
return res.length > 0? true: false;
}
}
File:auth.dart
import 'package:better_login/database_helper.dart';
enum AuthState{ LOGGED_IN, LOGGED_OUT }
abstract class AuthStateListener {
void onAuthStateChanged(AuthState state);
}
class AuthStateProvider {
static final AuthStateProvider _instance = new
AuthStateProvider.internal();
List<AuthStateListener> _subscribers;
factory AuthStateProvider() => _instance;
AuthStateProvider.internal() {
_subscribers = new List<AuthStateListener>();
initState();
}
void initState() async {
var db = new DatabaseHelper();
var isLoggedIn = await db.isLoggedIn();
if(isLoggedIn)
notify(AuthState.LOGGED_IN);
else
notify(AuthState.LOGGED_OUT);
}
void subscribe(AuthStateListener listener) {
_subscribers.add(listener);
}
void dispose(AuthStateListener listener) {
for(var l in _subscribers) {
if(l == listener)
_subscribers.remove(l);
}
}
void notify(AuthState state) {
_subscribers.forEach((AuthStateListener s) =>
s.onAuthStateChanged(state));
}
}
File: auth_provider.dart
import 'package:flutter/material.dart';
import 'package:better_login/auth.dart';
class AuthProvider extends InheritedWidget {
const AuthProvider({Key key, Widget child, this.auth}) : super(key: key, child: child);
final AuthStateListener auth;
#override
bool updateShouldNotify(InheritedWidget oldWidget) => true;
static AuthProvider of(BuildContext context) {
return context.inheritFromWidgetOfExactType(AuthProvider);
}
}
File: home_screen.dart
import 'package:flutter/material.dart';
import 'package:better_login/auth.dart';
import 'package:better_login/login_screen.dart';
import 'package:better_login/login_screen_presenter.dart';
import 'package:better_login/auth_provider.dart';
class HomeScreen extends StatelessWidget {
HomeScreen({this.authStateListener, this.authStateProvider});
final AuthStateListener authStateListener;
final AuthStateProvider authStateProvider;
void _signOut() async {
try{
authStateProvider.notify(AuthState.LOGGED_OUT);
authStateListener.onAuthStateChanged(AuthState.LOGGED_OUT);
}catch(e){
print(e);
}
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: new AppBar(
title: new Text("Home"),
actions: <Widget>[
new IconButton(icon: new Icon(Icons.exit_to_app), onPressed: (){_signOut();}),
],
),
body: new Center(
child: new Text("Welcome home!"),
),
);
}
}
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...
}
}