This question already has answers here:
The default 'List' constructor isn't available when null safety is enabled. Try using a list literal, 'List.filled' or 'List.generate'
(4 answers)
Flutter: List is deprecated? [duplicate]
(4 answers)
Closed 1 year ago.
List has been deprecated. How do I re-write the following code?
RosterToView.fromJson(Map<String, dynamic> json) {
if (json['value'] != null) {
rvRows = new List<RVRows>();
json['value'].forEach((v) {
rvRows.add(new RVRows.fromJson(v));
});
}
}
According to the official documentation:
#Deprecated("Use a list literal, [], or the List.filled constructor instead")
NOTICE: This constructor cannot be used in null-safe code. Use List.filled to create a non-empty list. This requires a fill value to initialize the list elements with. To create an empty list, use [] for a growable list or List.empty for a fixed length list (or where growability is determined at run-time).
You can do this instead:
RosterToView.fromJson(Map<String, dynamic> json) {
if (json['value'] != null) {
rvRows = <RVRows>[];
json['value'].forEach((v) {
rvRows.add(new RVRows.fromJson(v));
});
}
}
Another option is:
List<RVRows> rvRows = [];
Instead of:
rvRows = new List();
Write:
rvRows = [];
The error message tells you what to do. When I run dart analyze, I get:
info • 'List' is deprecated and shouldn't be used. Use a list literal, [],
or the List.filled constructor instead at ... • (deprecated_member_use)
Try replacing the use of the deprecated member with the replacement.
error • The default 'List' constructor isn't available when null safety is
enabled at ... • (default_list_constructor)
Try using a list literal, 'List.filled' or 'List.generate'.
The documentation for the zero-argument List constructor also states:
This constructor cannot be used in null-safe code. Use List.filled to create a non-empty list. This requires a fill value to initialize the list elements with. To create an empty list, use [] for a growable list or List.empty for a fixed length list (or where growability is determined at run-time).
Examples:
var emptyList = [];
var filledList = List<int>.filled(3, 0); // 3 elements all initialized to 0.
filledList[0] = 0;
filledList[1] = 1;
filledList[2] = 2;
var filledListWithNulls = List<int?>.filled(3, null);
var generatedList = List<int>.generate(3, (index) => index);
You also could use collection-for for both cases:
var filledList = [for (var i = 0; i < 3; i += 1) 0];
var filledListWithNulls = <int?>[for (var i = 0; i < 3; i += 1) null];
var generatedList = [for (var i = 0; i < 3; i += 1) i];
Related
I have this:
List<ForumCategories>? forumCategories;
var mainCats = List<ForumCategories>.empty(growable: true);
var subCats = <int, List<ForumCategories>>{};
Than this is what I do in order to populate it:
for (var i = 0; i < forumCategories!.length; i++) {
if (forumCategories![i].main == 0) {
subCats[forumCategories![i].slave]?.add(forumCategories![i]);
}
}
And than when I do:
var size = subCats.length;
print("SUBCATS: $size");
Output is always: SUBCATS: 0
This does not populate the map. Any idea why ?
because you're trying to add an item to a null List, see here:
if (forumCategories![i].main == 0) {
subCats[forumCategories![i].slave]?.add(forumCategories![i]);
}
subCats[forumCategories![i].slave] does not exist yet in your map, it's like you saying:
null.add(forumCategories![i]);
nothing will happen.
you need to initialize it by an empty List if it's null like this:
if (forumCategories![i].main == 0) {
(subCats[forumCategories![i].slave] ?? []).add(forumCategories![i]) // this will assign an empty list only the first time when it's null, then it adds elements to it.
}
now before adding elements to that list it will find the empty list to add.
This question already has answers here:
The default 'List' constructor isn't available when null safety is enabled. Try using a list literal, 'List.filled' or 'List.generate'
(4 answers)
Closed 8 months ago.
I try to make flutter null safety migration, I have this code working before and now I have this error on List(10)
The default 'List' constructor isn't available when null safety is enabled. Try using a list literal, 'List.filled' or 'List.generate'
Here is my code
List<CardModel> createCards() {
List<String> asset = [];
List(10).forEach((f) => asset.add('0${(asset.length + 1)}.png'));
List(10).forEach((f) => asset.add('0${(asset.length - 10 + 1)}.png'));
return List(20).map((f) {
int index = Random().nextInt(1000) % asset.length;
String _image =
'assets/' + asset[index].substring(asset[index].length - 6);
asset.removeAt(index);
return CardModel(
id: 20 - asset.length - 1, image: _image, key: UniqueKey());
}).toList();
}
Try:
List<CardModel> createCards() {
List<String> asset = [];
List.filled(10, null).forEach((f) => asset.add('0${(asset.length + 1)}.png'));
List.filled(10, null).forEach((f) => asset.add('0${(asset.length - 10 + 1)}.png'));
return List.filled(10, null).map((f) {
int index = Random().nextInt(1000) % asset.length;
String _image =
'assets/' + asset[index].substring(asset[index].length - 6);
asset.removeAt(index);
return CardModel(
id: 20 - asset.length - 1, image: _image, key: UniqueKey());
}).cast<CardModel>().toList();
}
Note that when you ommit the type param List(...) the default is dynamic, so: List<dynamic>() equals to List()
If List(N) create a list of type dynamic of size N with all values equals to null, then after null-safety you can replicate this by using List.filled(10, null).
And use cast<T>() to convert the list type to be able to use it as return value which expects the type CardModel.
This question already has answers here:
The default 'List' constructor isn't available when null safety is enabled. Try using a list literal, 'List.filled' or 'List.generate'
(4 answers)
Closed 1 year ago.
After upgrading to the latest version of flutter, I get a deprecation warning for all my Lists.
List<MyClass> _files = List<MyClass>();
=>'List' is deprecated and shouldn't be used.
Unfortunately, it does not give a hint of what to replace it with.
So what are we supposed to use instead now?
Dart SDK version: 2.12.0-141.0.dev
Flutter: Channel master, 1.25.0-9.0.pre.42
Ok, found it, it's just how to instantiate it:
List<MyClass> _files = [];
Edit: maybe the most common ones, a bit more detailed according to the docs:
Fixed-length list of size 0:
List<MyClass> _list = List<MyClass>.empty();
Growable list:
List<MyClass> _list = [];
//or
List<MyClass> _list = List<MyClass>.empty(growable: true);
Fixed length with predefined fill:
int length = 3;
String fill = "test";
List<String> _list = List<String>.filled(length, fill, growable: true);
// => ["test", "test", "test"]
List with generate function:
int length = 3;
MyClass myFun(int idx) => MyClass(id: idx);
List<MyClass> _list = List.generate(length, myFun, growable: true);
// => [Instance of 'MyClass', Instance of 'MyClass', Instance of 'MyClass']
List<MyClass> myList = <MyClass>[];
From:
_todoList = new List();
Change to:
_todoList = [];
old version
List<Widget> widgetList = new List<Widget>();
new version
List<Widget> widgetList = [];
I'm looking every where on the web (dart website, stackoverflow, forums, etc), and I can't find my answer.
So there is my problem: I need to write a function, that print a random sort of a list, witch is provided as an argument. : In dart as well.
I try with maps, with Sets, with list ... I try the method with assert, with sort, I look at random method with Math on dart librabry ... nothing can do what I wana do.
Can some one help me with this?
Here some draft:
var element03 = query('#exercice03');
var uneliste03 = {'01':'Jean', '02':'Maximilien', '03':'Brigitte', '04':'Sonia', '05':'Jean-Pierre', '06':'Sandra'};
var alluneliste03 = new Map.from(uneliste03);
assert(uneliste03 != alluneliste03);
print(alluneliste03);
var ingredients = new Set();
ingredients.addAll(['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']);
var alluneliste03 = new Map.from(ingredients);
assert(ingredients != alluneliste03);
//assert(ingredients.length == 4);
print(ingredients);
var fruits = <String>['bananas', 'apples', 'oranges'];
fruits.sort();
print(fruits);
There is a shuffle method in the List class. The methods shuffles the list in place. You can call it without an argument or provide a random number generator instance:
var list = ['a', 'b', 'c', 'd'];
list.shuffle();
print('$list');
The collection package comes with a shuffle function/extension that also supports specifying a sub range to shuffle:
void shuffle (
List list,
[int start = 0,
int end]
)
Here is a basic shuffle function. Note that the resulting shuffle is not cryptographically strong. It uses Dart's Random class, which produces pseudorandom data not suitable for cryptographic use.
import 'dart:math';
List shuffle(List items) {
var random = new Random();
// Go through all elements.
for (var i = items.length - 1; i > 0; i--) {
// Pick a pseudorandom number according to the list length
var n = random.nextInt(i + 1);
var temp = items[i];
items[i] = items[n];
items[n] = temp;
}
return items;
}
main() {
var items = ['foo', 'bar', 'baz', 'qux'];
print(shuffle(items));
}
You can use shuffle() with 2 dots like Vinoth Vino said.
List cities = ["Ankara","London","Paris"];
List mixed = cities..shuffle();
print(mixed);
// [London, Paris, Ankara]
Need to sort/order a list of data based on an undetermined number of columns (1 or more).
What i'm trying to do is loop through the desired columns and add an OrderBy or ThenBy based on their number to the query'd list, but i'm unsuccessful...
Done this, but it doesn't compile:
var query = GetAllItems(); //returns a IQueriable list of items
//for each selected column
for (int i = 0; i < param.Columns.Length; i++)
{
if (i == 0)
{
query = query.OrderBy(x => x.GetType().GetProperty(param.Columns[i].Name));
}
else
{
//ERROR: IQueriable does not contain a definition for "ThenBy" and no extension method "ThenBy"...
query = query.ThenBy(x => x.GetType().GetProperty(param.Columns[i].Data));
}
}
How can i resolve this issue? Or any alternative to accomplish this requirement?
SOLUTION: #Dave-Kidder's solution is well thought and resolves the compile errors i had. Just one problem, OrderBy only executes (actually sorts the results) after a ToList() cast. This is an issue because i can't convert a ToList back to an IOrderedQueryable.
So, after some research i came across a solution that resolve all my issues.
Microsoft assembly for the .Net 4.0 Dynamic language functionality: https://github.com/kahanu/System.Linq.Dynamic
using System.Linq.Dynamic; //need to install this package
Updated Code:
var query = GetAllItems(); //returns a IQueriable list of items
List<string> orderByColumnList = new List<string>(); //list of columns to sort
for (int i = 0; i < param.Columns.Length; i++)
{
string column = param.Columns[i].Name;
string direction = param.Columns[i].Dir;
//ex.: "columnA ASC"
string orderByColumn = column + " " + direction;
//add column to list
orderByColumnList.Add(orderBy);
}
//convert list to comma delimited string
string orderBy = String.Join(",", orderByColumnList.ToArray());
//sort by all columns, yay! :-D
query.OrderBy(orderBy).ToList();
The problem is that ThenBy is not defined on IQueryable, but on the IOrderedQueryable interface (which is what IQueryable.OrderBy returns). So you need to define a new variable for the IOrderedQueryable in order to do subsequent ThenBy calls. I changed the original code a bit to use System.Data.DataTable (to get a similar structure to your "param" object). The code also assumes that there is at least one column in the DataTable.
// using System.Data.DataTable to provide similar object structure as OP
DataTable param = new DataTable();
IQueryable<DataTable> query = new List<DataTable>().AsQueryable();
// OrderBy returns IOrderedQueryable<TSource>, which is the interface that defines
// "ThenBy" so we need to assign it to a different variable if we wish to make subsequent
// calls to ThenBy
var orderedQuery = query.OrderBy(x => x.GetType().GetProperty(param.Columns[0].ColumnName));
//for each other selected column
for (int i = 1; i < param.Columns.Count; i++)
{
orderedQuery = orderedQuery.ThenBy(x => x.GetType().GetProperty(param.Columns[i].ColumnName));
}
you should write ThenBy after OrderBy like this:
query = query
.OrderBy(t=> // your condition)
.ThenBy(t=> // next condition);