I'm new to model writing and I need your help.
I write a code like this:
import 'dart:js';
import 'dart:math';
List AllWords = [{"ID": 0, "Word": "This is words.", "Author": "Emir"}, {"ID": 1, "Word": "This is words.", "Author": "Jack"}];
class Words {
final int ID;
final String Word;
final String Author;
Words(this.ID, this.Word, this.Author);
void GetWords() {
final _random = new Random();
var Words = AllWords[_random.nextInt(AllWords.length)];
return Words;
}
}
My goal is to fetch a random word from the list when I use the GetWords Function. Is this code correct? How can I use this code I wrote in main.dart?
Thanks for help.
try this :
import 'dart:math' as math;
//your list is a map, not a `Words` class
//if your list is a `Words` class, it will be like this :
//final allWords = [Words(Id,words,author), Words()}
List<Map<String, Object?>> allWords = [
{"ID": 0, "Word": "This is words.", "Author": "Emir"},
{"ID": 1, "Word": "This is words.", "Author": "Jack"}
];
class Words {
final int iD;
final String word;
final String author;
Words({required this.iD, required this.author, required this.word});
factory Words.fromJson(Map<String, Object?> json) {
return Words(
iD: json['ID'] as int,
author: json['Author'] as String,
word: json['Word'] as String);
}
factory Words.getRandomWord() {
math.Random random = math.Random();
return Words.fromJson(allWords[random.nextInt(allWords.length - 1)]);
}
}
//Somewhere else in your code
Words myWord = Words.getRandomWord();
Related
In Dart, I can dynamically call a function using Function.apply:
Function.apply(foo, [1,2,3], {#f: 4, #g: 5});
gives exactly the same result as
foo(1, 2, 3, f: 4, g: 5).
Question: Does a similar thing exist for instantiating classes?
Expected result would look something like:
class foo {
final String boo;
int? moo;
foo({required this.boo, this.moo})
}
...
var params = {boo: 'A string value', moo: 121};
Class.apply(foo, params);
// Gives the result:
foo(boo: 'A string value', moo: 121);
Function.apply isn't type-safe, so you should avoid using it if you can.
If you really want to use it with a constructor, you can use it with constructor tear-offs (added in Dart 2.15), which are just Functions:
class Foo {
final String boo;
int? moo;
Foo({required this.boo, this.moo});
#override
String toString() => 'Foo(boo: "$boo", moo: $moo)';
}
void main() {
var params = {#boo: 'A string value', #moo: 121};
var result = Function.apply(Foo.new, [], params);
print(result); // Prints: Foo(boo: "A string value", moo: 121)
}
As far as I know, you can make use of static methods if you want to create an instance without using another instance. Here is a sample:
class Foo {
final String boo;
final int moo;
Foo({this.boo, this.moo});
static fromValues({String boo, int moo}) {
return Foo(boo: boo, moo: moo);
}
}
void main() {
var params = {#boo: 'A string value', #moo: 121};
var fooObject = Function.apply(Foo.fromValues, [], params);
print(fooObject);
print(fooObject.boo);
print(fooObject.moo);
}
Another way is to add 'call' function to class to make it's objects callable and use an object of the class to create new objects. Here is a sample:
class Foo {
final String boo;
final int moo;
Foo({this.boo, this.moo});
call({String boo, int moo}) {
return Foo(boo: boo, moo: moo);
}
}
void main() {
Foo aFoo = Foo(boo: 'nothing', moo: 0);
var params = {#boo: 'A string value', #moo: 121};
var fooObject = Function.apply(aFoo, [], params);
print(fooObject);
print(fooObject.boo);
print(fooObject.moo);
}
In Dart, how can I initialize a List of objects as a private class member?
Here is my Dartpad Link.
Here is my sample code.
// on dartpad: https://dartpad.dev/cfded55df52dd2bb37228d12c7ef049c
void main() {
Co co = Co();
print(co.getTag1()); //Out: profitable
print(co.getMgr1().fn); //Out: null
}
class Co {
List<String> _tags = ['profitable', '1999', 'public', 'NYSE'];
String getTag1() {
return _tags.first;
}
List<Mgr> _mgrs = List.from([
Mgr(
fn: 'Janice',
ln: 'Brown',
),
Mgr(
fn: 'Laura',
ln: 'Lopez',
),
Mgr(
fn: 'Linda',
ln: 'Oakley',
),
], growable: false);
Mgr getMgr1(){
return _mgrs.first;
}
}
class Mgr {
String fn;
String ln;
Mgr({String fn, String ln});
}
Specifically, how can I get the Output of Main >> print(co.getMgr1().fn); to be "Janice"? Thanks.
You are not storing the values passed in your constructor in the fields of Mgr, so the inputs are not being stored anywhere.
Change class Mgr to
class Mgr {
String fn;
String ln;
Mgr({this.fn, this.ln});
}
OR
class Mgr {
String fn;
String ln;
Mgr({String fn, String ln}) {
this.fn = fn;
this.ln = ln;
}
}
This stores the passed arguments in the fields of the class so that they can be accessed later.
Your initialization of the List is perfectly fine in this case.
I am using banklist in stateful widget. passing list to pageState using List<Bank> bankLists = this.widget.bankLists;
Que 1. Why I am getting error at gradientcolor: gradientBankCard("FFB74093","FFB74093")) that only static members can be accessed in initializer?
Que 2. How to pass const Data to gradientBankCard method . for Example I want to pass Color.fromRGBO(220, 132, 58, 1.0) to Arguments that gives error to.
I
List<Bank> bankLists = [
Bank(
id: "1",
name: "B1",
loanAmount: "₹ 250000",
emi: "₹11732",
intrest_rate: "11.69 % ",
processing_fee: "1.29 %",
tenure: "2 years",
gradientcolor: gradientBankCard('#e48634', '#e48634')), // //Error : Only static members can be accessed in initializers
Bank(
id: "2",
name: "B2",
loanAmount: "₹ 250000",
emi: "₹11732",
intrest_rate: "11.69 % ",
processing_fee: "1.29 %",
tenure: "2 years",
gradientcolor: gradientBankCard('#e48634', '#e48634')) //Error : Only static members can be accessed in initializers
];
Now I am using in my listing screen .
LinearGradient gradientBankCard(String startColor, String endColor){
return LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(hexToInt(startColor)),Color(hexToInt(endColor))]
);
}
Bank Model.dart
import 'package:flutter/material.dart';
class Bank {
final String id;
final String name;
final String loanAmount;
final String emi;
final String intrest_rate;
final String processing_fee;
final String tenure;
LinearGradient gradientcolor;
Bank({this.id, this.name, this.loanAmount, this.emi, this.intrest_rate,
this.processing_fee, this.tenure,this.gradientcolor});
}
The code
gradientcolor: gradientBankCard('#e48634', '#e48634')),
is executed before the class is fully initialized.
Initializers of fields like
List<Bank> bankLists = [...];
is executed before the super constructors are executed and at that point explicit or implict access to this. is not allowed because it would allow access to incompletely initialized state.
If you change
LinearGradient gradientBankCard(String startColor, String endColor){ ...
to
static LinearGradient gradientBankCard(String startColor, String endColor){
then there is no way to access this. and is therefore safe.
Im trying to parse json into a list of Products using Dart 2 for web.
I have the following Class:
class Product {
final String Problem;
final String Owner;
final String Description;
const Product({
this.Problem,
this.Owner,
this.Description,
});
factory Product.parse(Map<String, dynamic> json) {
print(json);
return new Product(
Problem: json["Problem"],
Owner: json["Owner"],
Description: json["Description"]
);
}
}
And I am trying to parse this using:
Stream<Product> getProducts() async* {
final payload = await HttpRequest.getString("products.json");
print(payload);
//var _json = (json.decode(payload));
print("break");
var list = json.decode(payload);
print(list);
//print(list);
final productList = (json.decode(payload) as List).cast<Map<String, dynamic>>();
}
However this fails with this error:
EXCEPTION: Type '_JsonMap' is not a subtype of expected type
'List'.
I can see that I have a list[Symbol(_original)] when I debug, but when I try to evaluate this, I returns as undefined.
I also tried
List list = json.decode(payload) as List;
List<dynamic> list = json.decode(payload);
List<dynamic> list = json.decode(payload) as List<dynamic>;
var list = (json.decode(payload)).cast<Map<String, dynamic>>();
var list = (json.decode(payload)).cast<Map<dynamic, dynamic>>();
but get the same error.
Json
{
"Product_One": {
"Owner": "test",
"Description": "test description",
"Theme_Objective": "test objective",
"Technical_details": "test technical details",
"Problem": "test",
"Solution": "test"
}
}
Your JSON does not contain any list, it's all maps.
When you try to cast a Map to List, it has to fail since maps are not lists.
Maybe you want to do:
final productList = (jsonDecode(payload) as Map).values.toList();
This gives you a list of the product maps, without the names that you don't appear to be using anyway.
How would I do the Dart equivalent of this Java code?
Class<?> c = Class.forName("mypackage.MyClass");
Constructor<?> cons = c.getConstructor(String.class);
Object object = cons.newInstance("MyAttributeValue");
(From Jeff Gardner)
The Dart code:
ClassMirror c = reflectClass(MyClass);
InstanceMirror im = c.newInstance(const Symbol(''), ['MyAttributeValue']);
var o = im.reflectee;
Learn more from this doc: http://www.dartlang.org/articles/reflection-with-mirrors/
(From Gilad Bracha)
Using built_mirrors you can do it next way:
library my_lib;
import 'package:built_mirrors/built_mirrors.dart';
part 'my_lib.g.dart';
#reflectable
class MyClass {
String myAttribute;
MyClass(this.myAttribute);
}
main() {
_initMirrors();
ClassMirror cm = reflectType(MyClass);
var o = cm.constructors[''](['MyAttributeValue']);
print("o.myAttribute: ${o.myattribute}");
}
This was an issue that has plagued me until I figured that I could implement a crude from method to handle the conversion of encoded Json Objects/strings or Dart Maps to the desired class.
Below is a simple example that also handles nulls and accepts JSON (as the string parameter)
import 'dart:convert';
class PaymentDetail
{
String AccountNumber;
double Amount;
int ChargeTypeID;
String CustomerNames;
PaymentDetail({
this.AccountNumber,
this.Amount,
this.ChargeTypeID,
this.CustomerNames
});
PaymentDetail from ({ string : String, object : Map }) {
var map = (object==null) ? (string==null) ? Map() : json.decode(string) : (object==null) ? Map() : object;
return new PaymentDetail(
AccountNumber : map["AccountNumber"] as String,
Amount : map["Amount"] as double,
ChargeTypeID : map["ChargeTypeID"] as int,
CustomerNames : map["CustomerNames"] as String
);
}
}
Below is it's implementation
PaymentDetail payDetail = new PaymentDetail().from(object: new Map());
PaymentDetail otherPayDetail = new PaymentDetail().from(object: {"AccountNumber": "1234", "Amount": 567.2980908});
Once again, this is simplistic and tedious to clone throughout the project but it works for simple cases.