In main.dart I call Quiz's function getQuestionText and getQuestionAnswer, getQuestionText works as expected but the other doesn't work, if returns me always the first result of the list. I just placed a debugPrint() and as expected getQuestionText() prints the correct number, getQuestionAnswer() always print 0, how is that possible?
class Quiz {
int _questionNumber = 0;
List<Question> _questions = [
Question('Some cats are actually allergic to humans', true),
Question('You can lead a cow down stairs but not up stairs.', false),
];
void nextQuestion() {
if (_questionNumber < _questions.length - 1) {
_questionNumber++;
}
}
String getQuestionText() {
print('$_questionNumber'); // <-- print the correct number
return _questions[_questionNumber].questionText;
}
bool getQuestionAnswer() {
print('$_questionNumber'); // <-- always print 0
return _questions[_questionNumber].questionAnswer;
}
}
Here how I call the functions
void checkAnswer(bool userAnswer) {
bool correctAnswer = Quiz().getQuestionAnswer();
setState(() {
if (userAnswer == correctAnswer) {
// right answer
} else {
// wrong pick
);
}
quiz.nextQuestion();
});
}
The problem is that you always create a fresh instance of your class Quiz by calling bool correctAnswer = Quiz().getQuestionAnswer(); inside checkAnswer().
Try to store the Quiz instance ouside:
const myQuiz = Quiz();
void checkAnswer(bool userAnswer) {
bool correctAnswer = myQuiz.getQuestionAnswer();
setState(() {
if (userAnswer == correctAnswer) {
// right answer
} else {
// wrong pick
}
myQuiz.nextQuestion();
});
}
Related
here is the code and when I run code it's print my result correctly but there is a null as result (in line 4) :
main() {
var ferrari = Car();
ferrari.armor = 85;
print(ferrari.armor);
}
class Car {
int? _armor;
int? get armor {
return _armor;
}
set armor(int? armor) {
if (armor != null && armor < 100) {
print(true);
} else {
print(false);
}
}
you have a variable that you give to it a custom getter and setter, so basically when you call the getter ferrari.armor it returns the _armor from your class, but since you see the _armor in your code will be always null because actaully you didn't give it any value in the setter, so it stays always null.
here propably what you wanted to do.
main() {
var ferrari = Car();
ferrari.armor = 85;
print(ferrari.armor);
}
class Car {
int? _armor;
int? get armor {
return _armor;
}
set armor(int? armor) {
if (armor != null && armor < 100) {
_armor = armor; // add this
print(true);
} else {
print(false);
}
}
}
In the set function, you need to set the _armor.
set armor(int? armor) {
if (armor != null && armor < 100) {
_armor = armor; // Set _armor to armor here.
print(true);
} else {
print(false);
}
}
I have var hasActivatedIndex = false.obs; and
#override
void onInit() {
super.onInit();
ever(hasActivatedIndex, (callback) {
print('hasActivatedIndex !!== $hasActivatedIndex'); // not activated
});
}
with following method I changed hasActivatedIndex true or false, and hope every time this ever() will get this boolean changed state and print something
int updateActivatedIndex({double scrollPy}){
activatedIndex = eventPyList.indexWhere((element) {
if (scrollPy >= element && scrollPy <= element + 20) {
hasActivatedIndex.value = true;
return true;
} else {
hasActivatedIndex.value = false;
showEventCard = false;
return false;
}
});
return activatedIndex;
}
The hasActivatedIndex.value has indeed changed to true or false, but ever() in onInit does not react to this change, why? thanks in advance for the explanation!
Hello I am trying to add future with the comments annotation but I have a problem I do not know to get the comment
My code is:
/// some comments
#Route.post('/')
Future<List> createTodo(Todo todo) async {
Map newTodo = {"id": todos.length + 1};
newTodo.addAll({"task": todo.task, "isCompleted": todo.isCompleted});
todos.add(newTodo);
return todos;
}
I do get Route annotiation with MethodMirror but I do not get any comments
void _addMethod(MethodMirror methodMirror) {
for (InstanceMirror item in methodMirror.metadata) {
var reflectee = item.reflectee;
if (reflectee is Route) {
print('true');
} else {
print('false');
}
}
}
How to fix code my code flutter and use plugin
filterContacts() {
setState(() {
List<Contact> _contacts = [];
_contacts.addAll(contacts);
if (searchController.text.isNotEmpty) {
_contacts.retainWhere(
(contact) {
String searchTerm = searchController.text.toLowerCase().trim();
String searchTermFlatten = flattenPhoneNumber(searchTerm);
String contactName = contact.displayName.toString().toLowerCase();
bool nameMatches = contactName.contains(searchTerm);
if (nameMatches == true) {
return true;
}
if (searchTermFlatten.isEmpty) {
return false;
}
var phone = contact.phones.firstWhere((phn) {
String phnFlattened = flattenPhoneNumber(phn);
return phnFlattened.contains(searchTermFlatten);
}, orElse: () => null);
return phone != null;
},
);
contactsFiltered = _contacts;
}
});
}
Flutter code How to fix code my code flutter and use plugin contacts_service,
this image is about a problem
contact.phones can be null, in this you need to check its value 1st then proceed,
you can use contact.phones?.firstWhere to handle this situation or
If you're sure it will have value, you can also do contact.phones!.firstWhere but I don't recommend this. You don't need to use orElse you want to pass null,
Item? phone = contact.phones?.firstWhere((phn) {
String phnFlattened = flattenPhoneNumber(phn);
return phnFlattened.contains(searchTermFlatten);
}, );
You can learn more about ?. !...
[how to fix now]
error code not complete
filterContacts() {
setState(() {
List<Contact> _contacts = [];
_contacts.addAll(contacts);
if (searchController.text.isNotEmpty) {
_contacts.retainWhere(
(contact) {
String searchTerm = searchController.text.toLowerCase().trim();
String searchTermFlatten = flattenPhoneNumber(searchTerm);
String contactName = contact.displayName.toString().toLowerCase();
bool nameMatches = contactName.contains(searchTerm);
if (nameMatches == true) {
return true;
}
if (searchTermFlatten.isEmpty) {
return false;
}
Item? phone = contact.phones?.firstWhere((phn) {
String phnFlattened = flattenPhoneNumber(phn);
return phnFlattened.contains(searchTermFlatten);
}, );
return phone != null;
},
);
contactsFiltered = _contacts;
}
});
}
I am working on live video streaming application with flutter. Everything is working fine except load more function. i am loading first 10 records from server and when user reach to last video i want to load more 10 records. I am using page controller to control the video pages. how can i make load more function to work. Any help would be appreciated.
Below is my page controller class
class VideoListController {
/// Construction method
VideoListController();
/// Snap to slide to realize page turning
void setPageContrller(PageController pageController) {
pageController.addListener(() {
int pageIndex = pageController.page.round();
_HomePageState home = _HomePageState();
if(pageIndex==home.videoDataList.length)
{
home.loadMore();
print("TAG loading more now");
}
var p = pageController.page;
if (p % 1 == 0) {
int target = p ~/ 1;
if (index.value == target) return;
//Play the current one, pause the others
var oldIndex = index.value;
var newIndex = target;
playerOfIndex(oldIndex).seekTo(0);
playerOfIndex(oldIndex).pause();
playerOfIndex(newIndex).start();
// carry out
index.value = target;
}
});
}
//Get specified indexçš„player
FijkPlayer playerOfIndex(int index) => playerList[index];
/// Total number of videos
int get videoCount => playerList.length;
/// Continue to add videos behind the current list and preload the cover
addVideoInfo(List<VideoModel> list) {
for (var info in list) {
playerList.add(
FijkPlayer()
..setDataSource(
Glob.ITEM_BASE_URL + info.post_video,
autoPlay: playerList.length == 0,
showCover: true,
)
..setLoop(0),
);
}
}
/// initialization
init(PageController pageController, List<VideoModel> initialList) {
addVideoInfo(initialList);
setPageContrller(pageController);
}
/// Current video sequence number
ValueNotifier<int> index = ValueNotifier<int>(0);
/// Video list
List<FijkPlayer> playerList = [];
///
FijkPlayer get currentPlayer => playerList[index.value];
bool get isPlaying => currentPlayer.state == FijkState.started;
/// Destroy all
void dispose() {
// Destroy all
for (var player in playerList) {
player.dispose();
}
playerList = [];
}
}
Below is load more function
Future<List<VideoModel>> loadMore() async {
Video menu = await getVideos();
if (menu.status == true) {
print("TAG res success is true " + menu.message);
setState(() {
videoDataList.addAll(menu.data);
start=videoDataList.length.toString();
print("TAG start " + start);
});
_videoListController.addVideoInfo(menu.data);
}
else {
print("No Data Found Paras");
}
return videoDataList;
}
Future<Video> getVideos() {
String data_type="application/x-www-form-urlencoded";
Map<String,String> headers = new Map();
headers['Content-Type'] = data_type;
return _netUtil.post(Glob.POST_LIST, body: {"count": count, "start": start,"type": type, "my_user_id": my_user_id},headers: headers).then((dynamic obj)
{
var results;
bool success = obj["status"];
print("TAG success =$success");
if (success == true)
results = Video.fromJson(obj);
else
results = Video.fromJsondata(obj);
return results;
});
}
Any help would be appreciated.
You're checking in the wrong way. You're actually checking the pageIndex value with the list size. The problem with that is index starts from 0 while length from 1 so pageIndex is never gonna match home.videoDataList.length. You have to check with home.videoDataList.length - 1
if(pageIndex == home.videoDataList.length - 1)
{
home.loadMore();
print("TAG loading more now");
}