How to generate file from model to flutter - flutter

Is it possible to convert the Model to a file and save it in the phone's storage? When it comes to non-standard variables String, int, bool... I mean there are variables that can't be converted to json.
This is my model:
class TronWalletModel {
final List<String> mnemonic;
final Uint8List seed;
final PrivateKey privateKey;
final PublicKey publicKey;
final String address;
final Uint8List signature;
TronWalletModel({
required this.mnemonic,
required this.seed,
required this.privateKey,
required this.publicKey,
required this.address,
required this.signature,
});
}
How can I save it to the phone's storage?

Related

Change the boolean value onclick and save to secured storage flutter

class Lessons {
final int? id;
final String? title;
final List<Resources> resources;
Lessons({
required this.id,
required this.title,
required this.resources,
});
}
class Resources extends Equatable {
final int? id;
final String? question;
final String? answer;
bool? bookmark;
Resources({
required this.id,
required this.question,
required this.answer,
required this.bookmark,
});
}
-these are my models, and have saved them using the secured storage flutter. How do i change just the bookmark and save it to secured storage?
i was able to change the bookmark but was unable to save it dynamically to secured storage.

flutter Erorr I cant deal with

I tried making a class then making a list of that class and I get an Erorr
the class I created:
class Transaction {
final String id;
final String title;
final double amount;
final DateTime date;
Transaction({
required this.id,
required this.title,
required this.amount,
required this.date,
});
}
Erorrs I get :
Try changing your variable name as it is clashing with the class name Transaction
and you can also use a different approach:
final List<Transaction>? transactionList;
trnasactionList.add(Transaction(id:1,title:'flutter' ....));
trnasactionList.add(Transaction(id:2,title:'flutter' ....));

List, verify register flutter

hello I am new to flutter and programming, if anyone can help me this is my question
I have one class with multiple products and I need to verify if they are in BD. So this is the class of products:
class CartItem {
final String name;
final double price;
final double quantity;
final String image;
final String cor;
final String tamanho;
CartItem({
required this.name,
required this.price,
required this.quantity,
required this.image,
required this.cor,
required this.tamanho,
});
}
And this is the URL to receive a true or false value depending on whether the product is in the BD or not
http://tzev.ddns/PTTC.1/PTTCProd?Stock=True&Reference=&Color=&Size=
First I have to store the value of the reference in the class, but then I don't know how to read one by one to receive the various values ​​of the API call

Store data model into Flutter Secure Storage

How do we store model data to flutter secure storage... or does it supports it?
I have a model like this... I load data from my API to this model... once I have data, I wanted to save it to the flutter secure storage and vice versa(load entire data to model from flutter secure storage)...
class MyUserModel {
MyUserModel({
this.authKey,
this.city,
this.contact,
this.email,
this.isContact,
this.userId,
});
String authKey;
String city;
String contact;
dynamic email;
bool isContact;
int userId;
}
Of course, I know we can read and write data like below... I am just checking if there is a way where we can directly write it from the model...
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
// Create storage
final storage = new FlutterSecureStorage();
// Read value
String value = await storage.read(key: key);
// Write value
await storage.write(key: key, value: value);
I saw hive supports this feature out of the box but I realized that it takes little time (2-3 sec) for initialization also Author is working on an alternative to hive due to two major blocks... the new database called Isar which clears all roadblock but it is still in development...
if it is possible then please share the sample code...
to save the object:
convert your object to map with toMap() method
serialize your map to string with serialize(...) method
save the string into secure storage
for restoring your object:
deserialize secure storage string to a map with deserialize(...) method
use fromJson() method to get your object
by that, you will serialize your data into a string and save and retrieve them.
class MyUserModel {
String authKey;
String city;
String contact;
dynamic email;
bool isContact;
int userId;
MyUserModel({
required this.authKey,
required this.city,
required this.contact,
required this.email,
required this.isContact,
required this.userId,
});
factory MyUserModel.fromJson(Map<String, dynamic> jsonData) =>
MyUserModel(
authKey: jsonData['auth_key'],
city: jsonData['city'],
contact: jsonData['contact'],
email: jsonData['email'],
isContact: jsonData['is_contact'] == '1',
userId: jsonData['user_id'],
);
}
static Map<String, dynamic> toMap(MyUserModel model) =>
<String, dynamic> {
'auth_key': model.authKey,
'city': model.city,
'contact': model.contact,
'email': model.email,
'is_contact': model.isContact ? '1' : '0',
'user_id': model.userId,
};
static String serialize(MyUserModel model) =>
json.encode(MyUserModel.toMap(model));
static MyUserModel deserialize(String json) =>
MyUserModel.fromJson(jsonDecode(json));
}
Usage:
final FlutterSecureStorage storage = FlutterSecureStorage();
await storage.write(key: key, value: MyUserModel.serialize(model));
MyUserModel model = MyUserModel.deserialize(await storage.read(key: key));
You can do this by encoding your Model into json saving it in Secure Storage and then decode the json and get the model back.
// Saving model into Storage
static Future<void> setMyUserModel(MyUserModel user) async {
await const FlutterSecureStorage().write(
key: 'user', value: user.toRawJson());
}
// Getting model from storage
static Future<MyUserModel> getMyUserModel() async {
return MyUserModel.fromRawJson(
await const FlutterSecureStorage().read(key: 'user') ??
'{}');
}
And of course you need to implement fromRawJson() and toRawJson() inside your model.
Sorry for the late reply :P.
To do this, encode your model into JSON and store it in secure storage. Later, decode the JSON to retrieve the model.
final storage = FlutterSecureStorage();
static const String modelData = "modelData";
// Saving model into Storage
static Future<void> setModel(user) async {
final jsonDataEncoded = jsonEncode(jsonData);
await storage.write(key: modelData , value: jsonDataEncoded);
}
//call this when you want to store your data to secured storage
ClassName.setModel(decodedResponse);//decode your json and send it here
//to read data from the local storage || secured storage
static Future<MyModel> getDataFromLocalStorage() async {
final jsonModel = await storage.read(key: modelData);
final jsonData = jsonDecode(jsonModel.toString());
final items = List.from(jsonData);
dataList = items.map((e) => MyModel.fromJson(e)).toList();
return dataList;
}

Ensure that only a certain string can be used in the constructor

I have a class as follows:
class QueueItem {
final String name;
final Type type;
final String imageUrl;
const QueueItem({
#required this.name,
#required this.type,
#required this.imageUrl,
});
}
Where Type is an enum. This does not work, so I would like an alternative which ensures that only certain strings can be chosen.
Your question are complicated since you don't state how you are going to use the class and what kind of check you want. For example, if you just want some runtime checking you can do:
class QueueItem {
final String name;
final String type;
final String imageUrl;
QueueItem({
#required this.name,
#required this.type,
#required this.imageUrl,
}) {
if (!['Christmas', 'New Years'].contains(type)) {
throw Exception('$type is not a valid input!');
}
}
}
This solution will work but does not have any statically guarantees so it can be difficult to use it in code since it is not any statically checks for which value is valid for type.
If type is restricted to a subset of values I think the best is to use a enum. You are saying that is not going to work but here is an example:
enum Type { christmas, newYears }
class QueueItem {
final String name;
final String type;
final String imageUrl;
factory QueueItem({
#required String name,
#required Type type,
#required String imageUrl,
}) {
switch (type) {
case Type.christmas :
return QueueItem._(name, 'Christmas', imageUrl);
case Type.newYears :
return QueueItem._(name, 'New Years', imageUrl);
default :
throw Exception('Unhandled enum value: $type');
}
}
QueueItem._(this.name, this.type, this.imageUrl);
}
This solution makes it more clear what intended value you want to use as argument. The signature of the factory constructor restricts the valid values but the value itself in the class are now a String.
I have also made a more advance solution based on same principle which outsource the logic into another class:
class ValidStringValue {
final String value;
const ValidStringValue._(this.value);
static ValidStringValue christmas = const ValidStringValue._('Christmas');
static ValidStringValue newYears = const ValidStringValue._('New Years');
static List<ValidStringValue> values = [christmas, newYears];
factory ValidStringValue.fromString(String input) =>
values.firstWhere((element) => element.value == input);
}
class QueueItem {
final String name;
final String type;
final String imageUrl;
QueueItem({
#required this.name,
#required ValidStringValue inputType,
#required this.imageUrl,
}) : type = inputType.value;
}
This solution does both have a statically way to assign a valid value and have ValidStringValue.fromString to create a value from a given input (which will crash if the input is not one of the accepted values).