RangeError (index): Invalid value: Not in inclusive range 0..2: 3 i cant fix - flutter

i have a problem this my list
class _FitnessAppState extends State<FitnessApp> {
String img_Header =
"https://images.unsplash.com/photo-1517836357463-d25dfeac3438?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80";
List trainingImage = [
"https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1631&q=80",
"https://images.unsplash.com/photo-1575052814086-f385e2e2ad1b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",
"https://media.istockphoto.com/photos/picture-of-people-running-on-treadmill-in-gym-picture-id879180126?k=20&m=879180126&s=612x612&w=0&h=WZ1Iqcqv5_rNTNslUscoMg9qAUoNiDG8kWBfVnpPapQ=",
];

your variables are:
String img_Header = "https://images.unsplash.com/photo-1517836357463-d25dfeac3438?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80";
List trainingImage = [
"https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1631&q=80",
"https://images.unsplash.com/photo-1575052814086-f385e2e2ad1b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80",
"https://media.istockphoto.com/photos/picture-of-people-running-on-treadmill-in-gym-picture-id879180126?k=20&m=879180126&s=612x612&w=0&h=WZ1Iqcqv5_rNTNslUscoMg9qAUoNiDG8kWBfVnpPapQ=",
];
the error of RangeError is happened in trainingImage variable as it is a List datatype, that's because you are trying to access an unavailable index inside a List, as example, your list trainingImage has only 3 elements which start by index 0 and ends by index 2:
print(trainingImage[0]);
// output: "https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1631&q=80"
print(trainingImage[1]);
// output: "https://images.unsplash.com/photo-1575052814086-f385e2e2ad1b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80"
print(trainingImage[2]);
// output: "https://media.istockphoto.com/photos/picture-of-people-running-on-treadmill-in-gym-picture-id879180126?k=20&m=879180126&s=612x612&w=0&h=WZ1Iqcqv5_rNTNslUscoMg9qAUoNiDG8kWBfVnpPapQ="
if you are trying to access the index 3 you will get the error of RangeError:
print(trainingImage[3]);
// output: RangeError (index): Invalid value: Not in inclusive range 0..2: 3
the solution is to always check if an index is available before accessing it:
// as example you want to access the index 3
int index = 3;
// 1st way
if(trainingImage.asMap().containsKey(index))
{
// run this if index 3 is available
}
// 2nd way
if(index < trainingImage.length && index >= 0)
{
// run this if index 3 is available
}

The code snippet that you have provided is fine. Maybe you are accessing wrong index of the list. Can you provide more information please?
However, I'll suggest you to rename the img_Header variable to imgHeader otherwise it will show lowerCamelCase warning.

Related

flutter hive putAt key error when delete from list

When I delete the employee, an error occurs in the key when I update the employee's data, and I do not understand where the problem is
this error:
Unhandled Exception: RangeError (index): Index out of range: index should be less than 4: 4
this code :
await employeerBox.putAt(
index,
employeerModel(
name: name.text.toString(),
phoneNumber: int.parse(phoneNumber.text),
location: location.text.toString(),
workDate: workDate.text.toString(),
workType: workType.text.toString(),
salary: double.parse(salary.text.toString())));
index = key
in delete by key no error but in put at give an error
I tried to update the data more than once and close and open the application, but to no avail

DynamoDB - How to upsert nested objects with updateItem

Hi I am newbie to dynamoDB. Below is the schema of the dynamo table
{
"user_id":1, // partition key
"dob":"1991-09-12", // sort key
"movies_watched":{
"1":{
"movie_name":"twilight",
"movie_released_year":"1990",
"movie_genre":"action"
},
"2":{
"movie_name":"harry potter",
"movie_released_year":"1996",
"movie_genre":"action"
},
"3":{
"movie_name":"lalaland",
"movie_released_year":"1998",
"movie_genre":"action"
},
"4":{
"movie_name":"serendipity",
"movie_released_year":"1999",
"movie_genre":"action"
}
}
..... 6 more attributes
}
I want to insert a new item if the item(that user id with dob) did not exist, otherwise add the movies to existing movies_watched map by checking if the movie is not already available the movies_watched map .
Currently, I am trying to use update(params) method.
Below is my approach:
function getInsertQuery (item) {
const exp = {
UpdateExpression: 'set',
ExpressionAttributeNames: {},
ExpressionAttributeValues: {}
}
Object.entries(item).forEach(([key, item]) => {
if (key !== 'user_id' && key !== 'dob' && key !== 'movies_watched') {
exp.UpdateExpression += ` #${key} = :${key},`
exp.ExpressionAttributeNames[`#${key}`] = key
exp.ExpressionAttributeValues[`:${key}`] = item
}
})
let i = 0
Object.entries(item. movies_watched).forEach(([key, item]) => {
exp.UpdateExpression += ` movies_watched.#uniqueID${i} = :uniqueID${i},`
exp.ExpressionAttributeNames[`#uniqueID${i}`] = key
exp.ExpressionAttributeValues[`:uniqueID${i}`] = item
i++
})
exp.UpdateExpression = exp.UpdateExpression.slice(0, -1)
return exp
}
The above method just creates update expression with expression names and values for all top level attributes as well as nested attributes (with document path).
It works well if the item is already available by updating movies_watched map. But throws exception if the item is not available and while inserting. Below is exception:
The document path provided in the update expression is invalid for update
However, I am still not sure how to check for duplicate movies in movies_watched map
Could someone guide me in right direction, any help is highly appreciated!
Thanks in advance
There is no way to do this, given your model, without reading an item from DDB before an update (at that point the process is trivial). If you don't want to impose this additional read capacity on your table for update, then you would need to re-design your data model:
You can change movies_watched to be a Set and hold references to movies. Caveat is that Set can contain only Numbers or Strings, thus you would have movie id or name or keep the data but as JSON Strings in your Set and then parse it back into JSON on read. With SET you can perform ADD operation on the movies_watched attribute. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html#Expressions.UpdateExpressions.ADD
You can go with single table design approach and have these movies watched as separate items with (PK:userId and SK:movie_id). To get a user you would perform a query and specify only PK=userId -> you will get a collection where one item is your user record and others are movies_watched. If you are new to DynamoDB and are learning the ropes, then I would suggest go with this approach. https://www.alexdebrie.com/posts/dynamodb-single-table/

How to find an item [array] in a dart list

I have a list with with an array of Objects added with this code:
_selectedItems.add([color, size, type]);
Each time I update the quantity of an item I have to call a method to verify if the list already have that item (if yes, update the quantity. if not, add the item and the quantity). So I tried this code:
print(_selectedItems.contains([color, size, type])); // searching if this product is in the list
But it always return false. I tried too verify the id's of each Object, but it returns false too. What I have to do to be able to reach the goal?
You can use .indexWhere() to find an object in a list and return the index:
Item _objectToInsert = Item();
int index = _selectedItems.indexWhere((item) => item.color.contains(_objectToInsert.color));
If index is -1, the object isn't in the list, else index will be the position of the obect in the list. So you can do:
if (index == -1) // add
_selectedItems.add(_objectToInsert);
else // update
_objectToInsert[index].color = _objectToInsert.color;

Dart using Null safe for variables

in this below code _invoiceInformation in first initialize is null and i'm trying to use dart null safe to manage that in my flutter applications
in this code although i used ? operation i still get error:
Error:
RangeError (index): Index out of range: no indices are valid: 0
what i want to try:
_invoiceInformation = Hive.box<InvoiceInformation>('invoice_information');
_province.text=_invoiceInformation?.getAt(0)?.province??'';
_province.text=_invoiceInformation?.getAt(0)?.province??'';
If the list _invoiceInformation is empty i.e having zero elements, then the null aware operator ? will allow you to access the element at 0, which is causing the error.
You will also have to check whether the list is empty or not before accessing its elements.
if(_invoiceInformation != null && _invoiceInformation.isNotEmpty) {
_province.text=_invoiceInformation.getAt(0)?.province ?? '';
}

How to access a Data Model [String: [String]] in UITableView with sections?

I'm trying to prep my Data Model so it can be used in a UITableView with sections.
var folderHolder: [String: [String]]?
folderHolder = ["Projects": ["All", "Recent"], "Smart Folders": ["Folder 1", "Folder 2", "Folder 3"]]
How can I access the keys and objects in this dictionary via an index (as needed by the UITableView)
I tried this in the playground and got stuck. Thank you for your help with this.
// Need number of Keys
// Expected result: 2
folderHolder!.count
// Need number of elements in Key
// Expected: All and Recent are in Projects, so 2 would be expected
folderHolder!["Projects"]
folderHolder!["Projects"]!.count
// How can I get this result by stating the index, e.g. writing 1 as a parameter instead of "Smart Folders"
folderHolder![1]!.count
// Need specific element
// Input parameter: Key index, Value index
// Expected: "Folder 2"
folderHolder![1]![1]
// I don't know why it only works when I state the key explicitly.
folderHolder!["Smart Folders"]![1]
Screenshot with Playground results
The way that dictionaries are set up, you cannot index them in the same way that you would index an array. Due to the Key: Value nature of dictionaries, the order is not important, and thus subscripting like so: folderHolder[1] will not work. Indexing like that would only work in an array, where the order is important and thus maintained.
The Swift Documentation here states that:
A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order.
Found out the solution after a bit more research:
The Dictionary keys need to be converted into an array. The array items can be accessed via an index (the section of the UITableView) and return the name of the Key. And the name of the key can be used to access the Value of the Dictionary (the row of the UITableView).
Here the correct playground data as a reference:
var folderHolder: [String: [String]]?
folderHolder = ["Projects": ["All", "Recent"], "Smart Folders": ["Folder 1", "Folder 2", "Folder 3"]]
let folderHolderArray = Array(folderHolder!.keys)
// Need number of Keys
// Expected: 2
folderHolder!.count
folderHolderArray.count
// Need number of elements in Key
// Expected: All and Recent are in Projects, so 2 would be expected
folderHolder!["Projects"]
folderHolder!["Projects"]!.count
// How can I get this result by stating the index, e.g. writing 1 as a parameter instead of "Smart Folders"
folderHolderArray[1]
// Need specific element
// Input parameter: Key index, Value index
// Expected: "Folder 2"
//folderHolder![1]![1]
let folderHolderSection = folderHolderArray[1]
let folders = folderHolder![folderHolderSection]
let folder = folderHolder![folderHolderSection]![1]