Error: Member not found: 'FlutterLocalNotificationsPlugin.initialize' - flutter

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?

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):

Unhandled Exception: This widget has been unmounted, in 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.

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.

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' on LoanSimulation Flutter

I want to showing list view from TextFormField to other pages
but the result in log say like this
E/flutter ( 9872): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
E/flutter ( 9872): #0 LoanResult.simulator (package:fluttermysql/models/LoanSimulationModel.dart:62:35)
E/flutter ( 9872): <asynchronous suspension>
E/flutter ( 9872): #1 _LoanSimulationState.result (package:fluttermysql/view/LoanSimulation.dart:29:5)
E/flutter ( 9872): <asynchronous suspension>
E/flutter ( 9872):
here is my LoanSimulationModel
static Future<LoanResult> simulator({String periodtime, String interestpermonth, String loanamountrequest, String idUser, String url}) async {
var url = "http://192.168.0.23/Api/loansimulation.php?periodtime=" + periodtime + "&interestpermonth=" + interestpermonth + "&loanamountrequest=" +loanamountrequest;
final response = await http.get(url,headers:{"Content-Type":
"application/json"});
var res = LoanResult.fromJson(jsonDecode(response.body));
return res;
}
and here is result async
void result() async {
LoanResult loanResult;
await LoanResult.simulator(
periodtime: periodtime,
interestpermonth: interestpermonth,
loanamountrequest: loanamountrequest,
url: BaseURL.kLoanSimulationUrl)
.then((value) => loanResult = value);
print(loanResult.Status);
if (loanResult.Status == true) {
Text(loanResult.message);
Navigator.pushReplacementNamed(context, Simulator.id);
} else {
_scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text(loanResult.message),
duration: Duration(seconds: 3),
));
}
}
here is example from React Native
how can i get this result with List? thank you

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