Class 'String' has no instance method 'tostring', Flutter - flutter

I am trying to generate a response from my chatbot(using dialogflow)
void response(query) async {
AuthGoogle authGoogle = await AuthGoogle(
fileJson: "Assets/amigo-pyhyyy-e2d1db5e1ee9.json").build();
Dialogflow dialogflow = await Dialogflow(
authGoogle: authGoogle, language: Language.english);
AIResponse aiResponse = await dialogflow.detectIntent(query);
setState(() {
messages.insert(0, {"data": 0,
"message": aiResponse.getListMessage()[0]["text"]["text"][0].tostring()
});
});
I get this error:
E/flutter ( 8166): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: Class 'String' has no instance method 'tostring'.
I tried adding dependencies in the pubspec.yaml:
dependencies:
to_string: ^1.2.1
dev_dependencies:
to_string_generator: ^1.2.1
but instead of getting a reply from the bot on the app, I am still getting a reply on my console.
Please have a look.
OKAYYYYY! I did change all of the instances to .toString() , instead of .tostring() (That was so stupid of me...- __________-)
But now I have an error:
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building:
type 'String' is not a subtype of type 'Widget'

Looking at the error message, aiResponse.getListMessage()[0]["text"]["text"][0] already returns a String value, so you can remove tostring() Lik Almasfiza already mentioned, normally it's toString() with a capital S, but should not be needed to convert a String to a String.

Related

Unhandled Exception: NoSuchMethodError: Class 'FirebaseAuthException' has no instance getter '_message'

Help me pls.
I have this error.
10Q
Unhandled Exception: NoSuchMethodError: Class 'FirebaseAuthException' has no instance getter '_message'.
E/flutter ( 5700): Receiver: Instance of 'FirebaseAuthException'
E/flutter ( 5700): Tried calling: _message
await _auth
.signInWithEmailAndPassword(
email: _emailTextEditingController.text.trim(),
password: _passwordTextEditingController.text.trim(),
)
.then((authUser) {
setState(() {
firebaseUser = authUser.user;
});
}).catchError((error) {
showDialog(
context: context,
builder: (c) {
return ErrorAlertDialog(
message: error._message == '[firebase_auth/user-not-found] There is no user record corresponding to this identifier. The user may have been deleted.'
? 'Email or password incorrect' : 'Error',
);
});
});
error._message == '[firebase_auth/user-not-found] There is no user record corresponding to this identifier. The user may have been deleted.'
? 'Email or password incorrect' : 'Error',
You are being told that there is no getter named _message for FirebaseAuthException. If you go to the code for that class, or the documentation (here) and look at the methods you have available to you,
_message is not one.
There is one there (getErrorCode) that you should be able to compare with much easier.
I think that the _message was called on null, I am not sure about this.

Flutter Futures: How can I make this StompClient connection awaitable with Futures?

I am using StompClient to connect to my gameservers websocket endpoint. For the sake of using FutureBuilder of Flutter I'd like to have async/await features with this client.
Therefore I wrapped the StompClient in the following way:
class CombatClient {
late StompClient _client;
Future<bool> connect() async {
_client = StompClient(
config: StompConfig.SockJS(
url: '${ServerGlobals.backendHost}/connect',
onConnect: (frame) async {
_client.subscribe(destination: "/gameserver/foo", callback: (data) => {print("foo: ${data.body}")});
},
),
);
_client.activate();
return await Future.doWhile(() => _client.connected);
}
}
In my main logic I am using the whole like this:
final combatClient = CombatClient();
await combatClient.connect();
However this does not work because of the following error:
E/flutter (23147): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'Null' is not a subtype of type 'FutureOr<bool>'
E/flutter (23147): #0 CombatClient.connect (package:app/combat/websocket/combat_client.dart:19:12)
E/flutter (23147): <asynchronous suspension>
E/flutter (23147): #1 _DebugCombatPageState.build.<anonymous closure> (package:app/debug/debug_combat_page.dart:61:27)
E/flutter (23147): <asynchronous suspension>
E/flutter (23147):
Regardless of the error I'd just love to know what the proper approach is. I always struggle when it comes to Futures etc. I can't find the right API usage to make my connection to the game server awaitable.
Quoted from #pskink
simply use Completer class instead of return await Future.doWhile(... - the docs say: "A way to produce Future objects and to complete them later with a value or error"

Unhandled Exception: NoSuchMethodError: The method 'map' was called on null - YouTube Api

I want to show videos on my channel with youtube api.
define videos: List? videos;
Here is the method with video listings:
factory VideosList.fromJson(Map<String, dynamic> json) => VideosList(
kind: json["kind"],
etag: json["etag"],
nextPageToken: json["nextPageToken"],
videos: List<VideosList>.from(
json["items"].map((x) => VideosList.fromJson(x))),
pageInfo: PageInfo.fromJson(json["pageInfo"]),
);
The error it gives when I run the application is: Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.
The line with the error:
videos: List<VideosList>.from(json["items"].map((x) => VideosList.fromJson(x))),
videos: List<VideosList>.from(json["items"].map((x) => VideosList.fromJson(x))).toList(),
I tried converting map to list it didn't work.

Exception: NoSuchMethodError occurs when i am casting response

I'm new in flutter and i'm trying to get list in list view. I searched a lot on this but i did not find something. Exception occurs when i'm trying to cast response of API and list view shows nothing.
Exception:
Exception: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'map' with matching arguments.
I/flutter (21020): Receiver: _LinkedHashMap len:2
I/flutter (21020): Tried calling: map<Post>(Closure: (dynamic) => Post)
I/flutter (21020): Found: map<K2, V2>((K, V) => MapEntry<K2, V2>) => Map<K2, V2>
final response = await client.get('http:url');
return compute(parsePosts, response.body);
}
List<Post> parsePosts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Post>((json) => Post.fromJson(json)).toList();
}
My JSON is like that
{
"status": "1",
"category": [
"Artificial Intelligence",
"big data",
"Cyber Security",
"Data Science",
"Software Development"
]
}
I want to show a list data in list view in Flutter. If you have any query or something regarding code then can ask me. Hope I will get best solution from this community.
Thanks in advance.

How to fix "the method 'cancel' called on null" while working with http requests flutter

I'm trying to athenticate using APIs from a flutter app but i get these errors everytime i click Login Button
final resp = await http.post("http://192.168.73.5/myserv/login.php", body: {
"login": "login",
"apid": "re0b53fd92d4b1593db1880az322d66ea9d4",
"email": _email,
"pass": _password,
});
var __data =json.decode(resp.body);
if (__data.length == 0) {
final snackbar = SnackBar(
content: Text('Server error'),
);
scaffoldKey.currentState.showSnackBar(snackbar);
} else if (__data[0]['resp'] == 'error') {
final snackbar = SnackBar(
content: Text('Password or email is incorrect!'),
);
scaffoldKey.currentState.showSnackBar(snackbar);
} else if (__data[0]['resp'] == 'sucess') {
final snackbar = SnackBar(
content: Text('You are logged in'),
);
scaffoldKey.currentState.showSnackBar(snackbar);
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) => HomeApp()));
}
}
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (29517): The following NoSuchMethodError was thrown while finalizing the widget tree:
I/flutter (29517): The method 'cancel' was called on null.
I/flutter (29517): Receiver: null
I/flutter (29517): Tried calling: cancel()
I/flutter (29517): When the exception was thrown, this was the stack:
My suggestion would be to take a look to your dispose method. There you might notice a statement calling a cancel method on something that was never initiated or used, only declared. In my case I got this error because at the disposed method I was trying to cancel a subscription to a Firebase service that I had not used. I never attached a listener to it, therefore when trying to cancel it, Flutter complained saying "the method cancel was called on null". I deleted the unnecessary line at dispose method and the error resolved. Hope the explanation helps somebody.