Random text output using FloatingButton (Flutter) - flutter

Need to output a random item from a list when I tap on the FloatingButton on the Text Widget. Tried many methods online but none seem to work.
Example:
I have 5 tasks:
Eat a sandwich
Take a nap
Call your friend
Run a kilometre
Buy some flowers.
Now, on a button press, I want one task displayed, like:
Your task is...
Call your friend.
Created a new list.dart file with list of items as well.
First post here. Any help is appreciated. Thanks!

Use a random number generator to get a random number between 0 and the length of the list.
import 'dart:math';
...
final listItem = ["item1", "item2", "item3"]; /// the list which has tasks
final String randomString = ''; /// initially defined as empty
...
Text(randomString), /// example widget where task is to be displayed
...
onTap: () {
// function called when there's a tap on the FloatingButton
Random random = new Random();
int randomIndex = random.nextInt(listItems.length); // where listItems is the list in list.dart file
final randomItem = listItems[randomIndex]; /// random item required
setstate((){
randomString = randomItem;
});
}

Related

How to create a method inside a provider class

I want to be clear and precise. I have a database with 260 variables, I have a data model class and a SQLiteHelper class. I'm using a provider and I have all the CRUD inside.
The problem comes because I have scrolleable page in which I want to be able to change all variables. Around 240 variables are int? and each one will have a button which do the same, convert it to zero if it is null or add 1 if it is an integer. I'm not using a normal callback because in that scrolleable page I use different reusable buttons and I want to know the value of the variable in child and parent widget. In the reusable buttons for change color and text, and in the parent widget(scrolleable page) to save them in SQlite at the end of the page with a save button.
This is my provider class
class DBProvider with ChangeNotifier {
final SQLiteHelper0 _db = SQLiteHelper0();
List<DB> _items = [];
Future<void> loadDB() async {
List<Map<String, dynamic>> data = await _db.charDB;
_items = data.map((DB) {
return DB(
id: charDB["id"],
name: charDB["name"],...// the rest of the CRUD
I'm trying something like that
dynamic increment(index){
if(_items[index] != int?){
return _items[index];
} else if (_items[index]! == null){
return _items[index]== 0;
}else { return _items[index] + 1;}
}
an then in the scrolleable page make another function like that
late DBProvider _dBProvier;
void _increment(index){setState(() {
_dBProvider.increment(index);
});}
I am having different problems, at times I think that nothing makes sense. But if it is a totally dumb way, please give me some direction to keep trying. This question is related with other question where I focused the problem in a different and wrong way Why this function is null?
Thanks.

in Flutter, make a list of api call inside one api call

In one of my flutter app, at first I want to call an api, which will return a list of item, and the item will be shown in a ListView. I also need to call another api for each item of the ListView to fetch description of that item and show the description to each item according to their id. How can I resolve this scenario. In RxJava, there is an operator called flatmap which did the same things without any hassle. But in flutter, How can I implement this. Here is my 2 function
class HomeRepositoryImpl extends HomeRepository {
HomeGraphQLService homeGraphQLService;
HomeMapper homeMapper;
HomeRepositoryImpl(HomeGraphQLService homeGraphQLService, HomeMapper homeMapper) {
this.homeGraphQLService = homeGraphQLService;
this.homeMapper = homeMapper;
}
#override
Future<List<Course>> getAllCourseOf(String className, String groupName) async {
final response = await homeGraphQLService.getAllCourseOf(className, groupName);
return homeMapper.toCourses(response).where((course) => course.isAvailable);
}
#override
Future<CourseProgressAndPerformance> getProgressAndPerformanceAnalysisOf(String subjectCode) async {
final response = await homeGraphQLService.getProgressAndPerformanceAnalysisOf(subjectCode);
return homeMapper.toProgressAndPerformance(response);
}
}
In the above class, first I call getAllCourseOf() function to get a list of course and show them in list view. I need to call getProgressAndPerformanceAnalysisOf(courseId) to fetch description of each item and show the description in each item of that list.
So what is recommended way to do so.
thanks in advance
I'm not sure on how the listing would be presented, my guess is you're looking for Stream and asyncMap()
Here's an example implementation that would give you a list of CourseProgressAndPerformance, this is the direction I'd investigate.
var perfList = Stream
.fromIterable(listOfCourses)
.asyncMap((course) => getProgressAndPerformanceAnalysisOf(courseId))
.toList();

Adding and Removing Items From Flutter Lists Dynamically

I have these two functions that should add the item onTap to the list, and then another one to delete the item. The first one (adding the item) works fine, but the delete one doesn't seem to delete anything. I suspect the issue is that the counter variable is not global, but for some reason it doesn't work fine when I add it globally (and I would need it to be). Here's the full code:
List<int> _totalPrice = [];
List<int> get totalPrice => _totalPrice;
here is the add item function
Future getTotal(item) async {
int counter = 0;
_totalPrice.add(int.parse(item));
_totalPrice.forEach((element) => counter += element);
print('LIST: $_totalPrice');
print('SUM: $counter');
return counter;
}
here is the delete function that doesn't remove anything
deleteSumItem(String item) {
_totalPrice.remove(item);
}
I think the issue is that the counter variable isn't global, I am not sure how to add it globally to change dynamically.
So, here your code shows that you are putting int in your _totalPrice list, but you are trying to remove the String from the list. It will not be found to be deleted.
So, you can change the data type of your list into String or you can write the below function to delete an item where the function only takes an int
deleteSumItem(int item) {
_totalPrice.remove(item);
}
Also you can remove an item by below line of code (If you have a custom type of data in your list):
_totalPrice.removeWhere((item) => item.price == '520')

Flutter FOR loop inside widget

So essentially what I am trying to achieve is this:
But apparently its not allowed in flutter.
I'm trying to load a LIST of restaurant items and their quantity values using a FOR loop and display them unto the app with a text widget. But with the current logic that I used I need to iterate and update the variable of x and range after displaying each item name along with its quantity from their respective lists. The problem here is I can't use the FOR loop within widgets as you would a normal FOR loop where you can place multiple statements within the FOR loop.
The snippet of code below is the logic I'm trying to achieve. It is similar to the code I'm implementing in flutter. The FOR loop portion is the only portion I'm kind of stuck with.
Still kind of new to Flutter, so any help or guidance would be appreciated. Thank you!
void main()
{
int x =0;
int range =0;
List<String> restaurauntNames = ['Jollibee','Chowking','Mcdonalds'];
List<int> orderNumber = [3,2,1];
List<int> itemQuantity = [1,1,2,3,1,3];
List<String> itemName= ['Jolly Spag','Chicken Joy','Peach Mango Pie','Chao Fan','Lauriat','Big Mac'];
for(String i in restaurauntNames)
{
print(i);
for(int z =0; z!=orderNumber[x];z++)
{
print(itemName[z+range]+'---------------'+ itemQuantity[z+range].toString());
}
range = range + orderNumber[x];
x++;
}
You can't put brace in for loop widget, I've got the same problem for quite some time and one the solution was to map the iterated list.
children: [
...restaurantNames.map((i){
print(i);
for(int z = 0; z != loadedOrder.orderNumber[x];z++){
return Text(loadedOrder.itemNames[z + range] + 'X' +loadedOrder.itemQuantity[z + range].toString());
}
range = range + orderNumber[x];
x++;
}).toList(),
],

List<Chip> chip = []; how do I add more chips?

I have a list of chips widgets.
These were created as follows:
List<Chips> myChips = [];
myChips.add(... values);
So now myChips contains a ton of Chip objects.
How do I display this?? How do I display a collection of chip objects that exist in a list??
for example, I'm hoping for :
Wrap(children: ... [myChips])
or something of that nature. But the parent widget that encloses it must be able to take in the entire myChips list.
Use this code:
var chip= new Chip();
myChips.add(chip);
for (final element in myChips) {
print(element);
}