Unhandled Exception: This widget has been unmounted, in flutter? - flutter

I am trying to submit data to the API but throwing a error that the widget is unmounted.
Here is the code:
SubmitRequest() async {
var newValue;
if(selectedIndex == 0){
newValue = 2;
}else if(selectedIndex == 1){
newValue = 3;
}else{
newValue = null;
}
var remark;
if(selectedIndex == 0){
remark = "Wrong";
}else if(selectedIndex == 1){
remark = "Invalid";
}else{
return null;
}
var url = Uri.parse(url);
var header = {
"API-Key": "eeee",
"Content-Type": "application/json",
};
final bdy = jsonEncode({
"action" :"dhdhd",
"token":"df23311",
"date": getCurrentDate().toString(),
});
var jsonresponse = await http.post(url, headers: header, body: bdy);
print(jsonresponse.statusCode);
if (jsonresponse.statusCode == 200) {
Utils.showToastSuccess("Submitted Successfully").show(context);
print("submit success");
}else{
Utils.showToastError("Submit Failed, Try Again").show(context);
}
}
when I try to run this the toast will not popup and throws an error:
E/flutter ( 615): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
E/flutter ( 615): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.
E/flutter ( 615): #0 State.context.<anonymous closure> (package:flutter/src/widgets/framework.dart:909:9)
E/flutter ( 615): #1 State.context (package:flutter/src/widgets/framework.dart:915:6)
E/flutter ( 615): #2 _WrongOrInvalidState.SubmitRequest (package:bmteacher/ui/History/invalid.dart:76:63)
E/flutter ( 615): <asynchronous suspension>
E/flutter ( 615):

When you call the method submitRequest(), are you using the keyword await? Because it the method you are trying to use a context that has already been disposed, so probably you app is not waiting the method submitRequest() to finish.

Related

Flutter Bluetooth Null Check Exception although null was checked

Here is the main() function. Here is the initializisation of the "flutter_isolate" library
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
...
class BTConnection {
BluetoothConnection? c;
Future<void> connect(address) async {
print('Connecting to the device ...');
BluetoothConnection connection =
await BluetoothConnection.toAddress(address);
c = connection;
print('Connected to the device');
FlutterIsolate.spawn(listenToData, connection);
}
Future<void> disconnect() async {
if (c != null) {
await c?.finish();
print("disconnected from device");
} else {
print("There is no bluetooth connection to disconnect");
}
}
#pragma('vm:entry-point')
Future<void> listenToData(connection) async {
print("listening ...");
await connection.input?.listen((Uint8List data) {
print('Data incoming: ${ascii.decode(data)}');
connection.output.add(data); // Sending data
}).onDone(() {
print('Disconnected by remote request');
});
}
}
Whenever I run the code and enter the correct MAC address in the text field, the function connect() is called and after a few seconds the message "Connected to the device" is printed. The following error message is then output:
E/flutter (26066): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter (26066): #0 FlutterIsolate.spawn
flutter_isolate.dart:28
E/flutter (26066): #1 BTConnection.connect
main.dart:110
E/flutter (26066): <asynchronous suspension>
E/flutter (26066): #2 _HomePageState.build.<anonymous closure>
main.dart:70
E/flutter (26066): <asynchronous suspension>
E/flutter (26066):

Error: Member not found: 'FlutterLocalNotificationsPlugin.initialize'

I am trying to implement notifications on flutter but I am getting a weird error:
I am calling the following function:
initInfo() {
var androidInitialize =
const AndroidInitializationSettings("#mipmap/ic_launcher");
var iOSInitialize = const IOSInitializationSettings();
var initializationsSettings =
InitializationSettings(android: androidInitialize, iOS: iOSInitialize);
FlutterLocalNotificationsPlugin.initialize(initializationsSettings,
onSelectNotification: (String? payload) async {
try {
if (payload != null && payload.isNotEmpty) ;
} catch (e) {
print(e);
}
return;
});
}
I am getting the following error:
Instance member 'initialize' can't be accessed using static access.
here is the error log:
: Error: Member not found: 'FlutterLocalNotificationsPlugin.initialize'.
lib/navigator_view.dart:81
FlutterLocalNotificationsPlugin.initialize(initializationsSettings,
^^^^^^^^^^
Restarted application in 271ms.
I am trying to follow this video: https://youtu.be/AUU6gbDni4Q?t=845
I was able to get pass the initial error by doing this::
initInfo() {
var androidInitialize =
const AndroidInitializationSettings("#mipmap/ic_launcher");
var iOSInitialize = const IOSInitializationSettings();
var initializationsSettings =
InitializationSettings(android: androidInitialize, iOS: iOSInitialize);
var fln = FlutterLocalNotificationsPlugin(); // new code
fln.initialize(initializationsSettings,
onSelectNotification: (String? payload) async {
try {
if (payload != null && payload.isNotEmpty) ;
} catch (e) {
print(e);
}
return;
});
}
but now I am getting the following error:
/flutter (23250): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: MissingPluginException(No implementation found for method initialize on channel dexterous.com/flutter/local_notifications)
E/flutter (23250): #0 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:294
E/flutter (23250): <asynchronous suspension>
E/flutter (23250): #1 AndroidFlutterLocalNotificationsPlugin.initialize
package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:85
E/flutter (23250): <asynchronous suspension>
E/flutter (23250):
should I not be doing this change?

Why doesn't my method work in DioError catch in Flutter/Dart?

I am making a request to my database like this:
//Airtable (find a record)
void airtableFind() async {
try {
final response = await Dio().get(
'https://api.airtable.com/v0/'+projectBase+'/'+recordName,
queryParameters: {
'filterByFormula': 'SEARCH('+'"'+username+'"'+',{Name})' // Searches the value 'Cactus' in the {'Short description'} field.
},
options: Options(
contentType: 'Application/json',
headers: {
'Authorization': 'Bearer'+' '+apiKey,
'Accept': 'Application/json',
},
),
);
// TODO: Whatever you want to do with the response. A good practice is to transform it into models and than work with them
// print(response);
// print(response.data['records'][0]['id']);
idString = response.data['records'][0]['id'];
// if (idString.isNotEmpty) (
// showInvalidUsernameDialog(context)
// // TODO: Need to inform about success
// );
} on DioError catch (e) {
// TODO: Error handling
if (e.response != null) {
// print(e.response.data);
print(e);
showInvalidUsernameDialog(context);
} else {
// print(e.request);
print(e.message);
showInvalidUsernameDialog(context);
}
}
}
If my user enters the correct word (username), then everything works correctly. But there is always a risk that a person is mistaken. And I want to indicate this with the showInvalidUsernameDialog(context); dialog box, but for some reason it does not pop up.
I see errors in the console:
I/flutter(4484): DioError [DioErrorType.response]: Http status error [422]
I/flutter ( 4484): Source stack:
I/flutter(4484): #0 DioMixin.fetch(package:dio/src/dio_mixin.dart:488:35)
I/flutter ( 4484): #1 DioMixin.request (package:dio/src/dio_mixin.dart:483:12)
I/flutter ( 4484): #2 DioMixin.patch (package:dio/src/dio_mixin.dart:249:12)
I/flutter(4484): #3 _RouteState.airtableUpdate(package:example/main.dart:1498:36)
I/flutter ( 4484): #4 _RouteState.build.<anonymous closure> (package:example/main.dart:1617:13)
I/flutter ( 4484): #5 _RouteState.build.<anonymous closure> (package:example/main.dart:1612:24)
I/flutter(4484): #6 EditableTextState._finalizeEditing (package:flutter/src/widgets/editable_text.dart:2148:18)
I/flutter(4484): #7 EditableTextState.performAction(package:flutter/src/widgets/editable_text.dart:1999:9)
I/flutter(4484): #8 TextInput._handleTextInputInvocation(package:flutter/src/services/text_input.dart:1746:37)
I/flutter ( 4484): #9 MethodChannel._handleAsMethodCall (package:flutter/src/services/platform_channel.dart:404:55)
I/flutter ( 4484): #10 MethodChannel.setMethodCallHandler.<anonymous closure> (package:flutter/src/services/platform_chan
E/flutter ( 4484): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0
E/flutter ( 4484): #0 List.[] (dart:core-patch/growable_array.dart:264:36)
E/flutter ( 4484): #1 _RouteState.airtableFind (package:example/main.dart:1473:42)
E/flutter ( 4484): <asynchronous suspension>
E/flutter ( 4484):
And that's to be expected, since I'm deliberately entering the wrong username. But I want to get not only a list of errors in the console, but also a dialog box. Why doesn't it appear?
The dialog box call method is correct. I put it in the part of the code that fires when the username is valid. It appears exactly as intended.
But why doesn't this method work in this part of the code?
on DioError catch (e) {
// TODO: Error handling
if (e.response != null) {
// print(e.response.data);
print(e);
showInvalidUsernameDialog(context);
} else {
// print(e.request);
print(e.message);
showInvalidUsernameDialog(context);
}
And how can I make this dialog appear in case of an error?
Edit 1. _RouteState.airtableFind (package:example/main.dart:1473:42) is referring to idString = response.data['records'][0]['id'];. This happens when my user enters their login incorrectly.
Use catch directly and check if its of type DioError. This is a known behaviour.. Its not catching 400 or 500 errors
https://github.com/flutterchina/dio/issues/1198
try{
}catch(e){
print(e.toString());
}
or
try{
}catch(e){
if(e is DioError)
{
}
}

Unhandled Exception: NoSuchMethodError: Class 'Future<dynamic>' has no instance method '[]' when getting data from openweathermap

I am building a weather app using OpenWeatherMap API.
Whenever I am passing latitude and longitude then I am getting the data correctly:
Future<dynamic> getWeatherData(double latitude, double longitude) async{
Network network = Network();
var weatherData = await network.getJson("https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&appid=$APP_ID&units=metric");
return weatherData;
}
I am using weatherData like this:
void updateWeather(dynamic weatherData){
Weather weather = Weather();
setState(() {
if (weatherData == null){
temperature = 0;
temperatureIcon = "💔";
temperatureText = "Can't find weather, make sure GPS is on";
return;
}
temperature = weatherData["main"]["temp"];
int condition = weatherData["weather"][0]["id"];
temperatureIcon = weather.getWeatherIcon(condition);
temperatureText = weather.getMessage(temperature);
});
I am using temperatureIcon and temperatureText in Text() widgets below.
Now I was adding the feature to get weather by searching city name:
var cityName = await Navigator.push(context, MaterialPageRoute(
builder: (context){
return Search();
}
));
if (cityName != null && cityName.toString().isNotEmpty){
Weather weather = Weather();
var weatherData = weather.getWeatherDataCity(cityName);
updateWeather(weatherData);
}
getWeatherDataCity():
Future<dynamic> getWeatherDataCity(String cityName) async{
Network network = Network();
var weatherData = await network.getJson("https://api.openweathermap.org/data/2.5/weather?q=$cityName&appid=$APP_ID&units=metric");
return weatherData;
}
but when I run this code I get this exception:
E/flutter ( 3250): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: Class 'Future<dynamic>' has no instance method '[]'.
E/flutter ( 3250): Receiver: Instance of 'Future<dynamic>'
E/flutter ( 3250): Tried calling: []("main")
E/flutter ( 3250): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter ( 3250): #1 WeatherScreenState.updateWeather.<anonymous closure> (package:clima/screens/weather_screen.dart:39:32)
E/flutter ( 3250): #2 State.setState (package:flutter/src/widgets/framework.dart:1088:30)
E/flutter ( 3250): #3 WeatherScreenState.updateWeather (package:clima/screens/weather_screen.dart:32:5)
E/flutter ( 3250): #4 WeatherScreenState.build.<anonymous closure> (package:clima/screens/weather_screen.dart:86:25)
E/flutter ( 3250): <asynchronous suspension>
Why am I getting this exception?
The JSON data received is the same when I put city name or latitude and longitude.
Network.getJson():
class Network{
Future<dynamic> getJson(String url) async{
Response response = await get(Uri.parse(url));
print(response.body);
return response.statusCode >= 200 ? jsonDecode(response.body) : null;
}
}
Try awaiting for this function:
var weatherData = await weather.getWeatherDataCity(cityName);
Life would also be a lot easier and code would make more sense if you eliminated all the dynamic and var and used objects.

Converting object to an encodable object failed in http call

I'm getting a response from API but there is an error.
I'm not getting any response where I'm calling topicpurchased()
Future<bool> topicpurchased(int topicid, String title) async {
var map = new Map<String, dynamic>();
map['topicid'] = topicid;
map['title'] = title;
var data = json.encode(map);
print(data);
var response = await http.post(Constants.ApiBaseUrl + '/topicpuchased',
headers: headers, body: data);
if (response.statusCode == 200) {
print("topicpurchasede" + response.body);
TrueOrFalse trueOrFalse = TrueOrFalse.fromJson(json.decode(response.body));
if (trueOrFalse.status == "sucess") {
print(" 👍👍👍👍👍👍👍👍");
return true;
} else {
print("something went wrong" + trueOrFalse.status);
return false;
}
} else {
throw Exception('Failed');
}
}
error in console as follows
I/flutter (22130): topicpurchasede{"status":"sucess"}
I/flutter (22130): datamodel sucess
I/flutter (22130): 👍👍👍👍👍👍👍👍
E/flutter (22130): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Converting object to an encodable object failed: Instance of 'Future<String>'
E/flutter (22130): #0 _JsonStringifier.writeObject (dart:convert/json.dart:688:7)
E/flutter (22130): #1 _JsonStringifier.writeMap (dart:convert/json.dart:769:7)
E/flutter (22130): #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:724:21)
E/flutter (22130): #3 _JsonStringifier.writeObject (dart:convert/json.dart:679:9)
E/flutter (22130): #4 _JsonStringStringifier.printOn (dart:convert/json.dart:877:17)
E/flutter (22130): #5 _JsonStringStringifier.stringify (dart:convert/json.dart:862:5)
E/flutter (22130): #6 JsonEncoder.convert (dart:convert/json.dart:262:30)
E/flutter (22130): #7 JsonCodec.encode (dart:convert/json.dart:172:45)
thanks in advance.
First, you have to call the function using await because it's a Future:
Example:
bool response = await topicpurchased(topicid,title);
Future<bool> topicpurchased(int topicid, String title) async {
var map = new Map<String, dynamic>();
map['topicid'] = topicid;
map['title'] = title;
var data = json.encode(map);
print(data);
var response = await http.post(Constants.ApiBaseUrl + '/topicpuchased',
headers: headers, body: data);
if (response.statusCode == 200) {
print("topicpurchasede" + response.body);
//here could be the bug
TrueOrFalse trueOrFalse = TrueOrFalse.fromJson(json.decode(response.body));
if (trueOrFalse.status == "sucess") {
print(" 👍👍👍👍👍👍👍👍");
return true;
} else {
print("something went wrong" + trueOrFalse.status);
return false;
}
} else {
//second: here too you can send a bool return because you function has declare a
//bool response
throw Exception('Failed');
}
}
Third: The error seems to come from your model, you can comment on this line and run the application to see if the error comes from there