how transform text to List flutter - list

I use this code to have two custom textfields (TodTextfield) and a button (TodButton).
Padding(
padding: const EdgeInsets.only(top: 20),
child: TodTextField.formField(
key: _dayKeys[1],
controller: _facebookController,
labelText: localizations.hintFacebook,
textInputAction: TextInputAction.next,
),
),
Padding(
padding: const EdgeInsets.only(top: 20),
child: TodTextField.formField(
key: _dayKeys[2],
controller: _siteController,
labelText: localizations.hintSite,
textInputAction: TextInputAction.done,
),
),
TodButton.elevated(
label: localizations.btnConfirm,
replaceOnPressed: true,
onPressed: () async {
final patch = await Connection()
.accessoryData(
unitId: widget.connectedUnit.id.toString(),
contactEmail: _emailController.text,
contactPhone: _phone,
//socialAccount: SocialAccount?,/// I NEED HELP HERE
)
},
),
class SocialAccount {
SocialAccount({
required this.type,
required this.link,
});
factory SocialAccount.fromJson(Map<String, dynamic> json) {
try {
return SocialAccount(
type: AccountType.fromName(json.get('type') as String),
link: json.get('link') as String,
);
} catch (e, stack) {
logger.e('Failed to deserialize SocialAccount', e, stack);
rethrow;
}
}
Map<String, dynamic> toJson() => {
'type': type.toString(),
'link': link,
};
final AccountType type;
final String link;
}
now I need to take the data entered by the user in the two Textfields to make a Patch, this one:
"social_accounts": [{
"type": "facebook" | "instagram" | "website" | "twitter"
"link": "string"
}]
SocialAccount is the class I made myself as a Model to manage that data.
The problem is that I don't know how to take those two texts I have, to put them in the call which is a list ..

Related

Flutter property values of a Map all treated as strings

I have a list like this a = [{'one': 'one', 'two': null, 'three': [{'four': 'four'}]}]
I send it to a function to use it in a post request which in the body should receive a Map, so what I did was this to a[0], the problem is that I get this error The getter 'length' was called on null
I start to review and it treats all the property values as if they were Strings, even the nested list 'three': [{'four': 'four'}], I have tried to send the post in this way http.post (url, body: (recurrence [0] as Map)) but it has not worked, it always gives me the same error, even if in the body I put the properties by hand in the body: {'new property': a [0] [' tres']}, how should one act to solve this problem? Thank you very much for your help
Code:
void _ordersGet() async {
await http.get(url).then((value) {
setState(() {
orders = jsonDecode(value.body);
}
}
orders is sent to a new widget: orderList(orders)
orderList is a listView
ListView.builder(
shrinkWrap: true,
primary: false,
itemCount: orders.length,
itemBuilder: (orders, index) {
return return Card(
elevation: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(orders[index]['facts']),
SizedBox(
width: 4,
),
Text('Cantidad : '),
Text(orders[index]['ITEMS'][0]['jeans']),
SizedBox(
width: 4,
),
IconButton(
onPressed: () => _reorderData(context, orders[index]),
icon: Icon(
Icons.replay_outlined,
color: Theme.of(context).accentColor,
)),
],
),
);
},
);
_reorderData is a function that make a get request, the info in shipped to ReorderModal
ReorderModal it only shows the information and has a button
void _reorderData(BuildContext ctx, order) async {
var data;
var url = 'serverAddress/${order['facts']}';
await http.get(url).then((value) {
data = jsonDecode(value.body);
data[0]['CORPORATION'] = order['corporation'];
showModalBottomSheet(
context: ctx,
builder: (_) {
return ReorderModal(data);
});
}).catchError((onError) {});
}
class ReorderModal extends StatelessWidget {
final List data;
ReorderModal(this.data);
void orderSend(orderInfo) async {
var url = 'serverAddress';
await http.post(url, body: orderInfo[0]).then((value) {
print(jsonDecode(value.body));
}).catchError((onError) {
print(onError);
});
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10),
child: Column(children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Column(
children: [
ElevatedButton(
onPressed: () {
orderSend(data);
//print(data);
},
child: Text('ONE Click'))
]),
);
}
}
when i press the ONE Click button execute the function orderSend, orderSend make a post request and the problem described above
This is the simplified code, I know it must be something very simple, but it is giving me a lot of work to solve

Save list getting from JSON URL in firestore collection

My small app, is getting list of users from JSON link then store it in the List, I wanna this list into usersCollection collection ref of firestore
my code
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:yat_flutter_app/main.dart';
import 'usersList.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
CollectionReference usersCollection =
FirebaseFirestore.instance.collection('users');
Future<List<User>> getUsers() async {
var data = await http
.get("https://www.json-generator.com/api/json/get/bYKKPeXRcO?indent=2");
var jasonData = json.decode(data.body);
List<User> users = [];
for (var i in jasonData) {
User user = User(i["index"], i["about"], i["name"], i["picture"],
i["company"], i["email"]);
users.add(user);
}
return users;
}
#override
Widget build(BuildContext context) {
List<User> usersList = getUsers() as List<User>;
return Container(
child: Column(
children: [
FutureBuilder(
future: getUsers(),
builder: (BuildContext context, AsyncSnapshot asyncSnapshop) {
if (asyncSnapshop.hasData) {
return Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: asyncSnapshop.data.length,
itemBuilder: (BuildContext context, int index) {
return Card(
elevation: 5,
color: Colors.cyan[50],
child: ListTile(
trailing: Icon(Icons.share),
title: Text(asyncSnapshop.data[index].name, style: TextStyle(fontFamily: 'Tahoma',fontSize: 20,fontWeight: FontWeight.bold),),
leading: CircleAvatar(
backgroundImage: NetworkImage(
asyncSnapshop.data[index].picture +
asyncSnapshop.data[index].index.toString() +
".jpg"),
),
subtitle: Text(asyncSnapshop.data[index].email,style: TextStyle(fontFamily: 'Tahmoma',fontSize: 18),),
onTap: (){
Navigator.push(context, new MaterialPageRoute(builder: (context)=>
detailsPage(asyncSnapshop.data[index])
));
},
onLongPress: ()=>
Fluttertoast.showToast(
msg: asyncSnapshop.data[index].name,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.green[900],
textColor: Colors.white,
fontSize: 16.0
),
),
);
}),
);
} else {
return Text("Loading, please wait...");
}
},
),
ElevatedButton(
child: Text('Save data'),
onPressed: () => {
usersCollection.add(getUsers()); // here's I am trying to add the result of getUsers into usersCollection
}),
],
),
);
}
}
To push an object to Firestore you need to convert your object to map.
You can just add this function to your class:
Map<String, dynamic> toMap() {
return {
'field1': value1,
'field2': value1,
};
}
To push a List , you need to convert all objects to map, you can do it with following method:
static List<Map> ConvertToMap({List myList }) {
List<Map> steps = [];
myList.forEach((var value) {
Map step = value.toMap();
steps.add(step);
});
return steps;
}
Or simply , see how to convert List to Map
I hope it will be useful
To push this list to Firestore you need to fromJson and toJson methods in your model class
factory User.fromJson(Map<String, dynamic> data){
return User(
index: data['index'] as int,
about: data['about'] as String,
name: data['name'] as String,
picture: data['picture'] as String,
company: data['company'] as String,
email: data['email'] as String );
}
Map<String, dynamic> toJson(){
return {
"index": index,
"about" : about,
"name" : name,
"picture" : picture,
"company" : company,
"email" : email,
};
}
instead that I would like to suggest using json_serializable library
then you need to do some changes in your future method like this
getUsers().then((users) {
// add users to map
});
and then you can use fromJson method to push it to firestore database
Firebase realtime database and firestore are no SQL databases where data will be stored in Parent child relation or Tree structure.
For you to store list of data you can convert your list into Map
Map can be initialised as follows
Map<String, String> toMap() {
return {
'Fruit': "Mango",
'Flower': "Lotus",
'Vegetable': "Potato",
};
}
After you have Map you can set value to the firestore. You can use the below code to set value
Map<String, Object> city = new Map<>();
//Loop through your list and load Map (City) values
db.collection("cities").document("LA").set(city)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
You can convert List of items to map using this
Java: How to convert List to Map

How to filter a List of Map for creating another List of Map as the result of a search functionality

I am trying to implement a search function in my app for filtering between many entries in a list of map.
The data structure that I have is:
[{Entry: Accident , Definition: An unexpected event or circumstance without deliberate intent.}, {Entry: Accident Insurance , Definition: Insurance for unforeseen bodily injury.}, {Entry: Accident Only , Definition: An insurance contract that provides coverage, singly or in combination, for death, dismemberment, disability, or hospital and medical care caused by or necessitated as a result of accident or specified kinds of accident.}, {Entry: Accident Only or AD&D , Definition: Policies providing coverage, singly or in combination, for death, dismemberment, disability, or hospital and medical care caused by or necessitated as a result of accident or specified kinds of accidents. Types of coverage include student accident, sports accident, travel accident, blanket accident, specific accident or accidental death and dismemberment (ad&d).} ... etc, etc. ]
These are the contents of the .json file:
[
{
"Entry": "Accident ",
"Definition": "An unexpected event or circumstance without deliberate intent."
},
{
"Entry": "Accident Insurance ",
"Definition": "Insurance for unforeseen bodily injury."
},
[... and looooots of many other "Entry", "Definition" pairs like these]
{
"Entry": "Written Premium ",
"Definition": "The contractually determined amount charged by the reporting entity to the policyholder for the effective period of the contract based on the expectation of risk, policy benefits, and expenses associated with the coverage provided by the terms of the insurance contract."
}
]
Each map entry creates one button with an associated definition.
The user is queried for a search query to get only the button(s) that satisfy the query result.
I include the .dart file that I am trying to implement:
import 'package:flutter/material.dart';
import 'listentries.dart';
import 'destination.dart';
import 'dart:convert';
// ignore: must_be_immutable
class searchScreen extends StatefulWidget {
final String searchTerm;
searchScreen({this.searchTerm});
#override
_SearchScreenState createState() => new _SearchScreenState();
}
class _SearchScreenState extends State<searchScreen> {
#override
Widget build(BuildContext context) {
final widgetElements = new ListEntries(); // From listentries.dart
var searchedItems =
widgetElements; // Copy from widgetElements filter out from here
var query;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
title: Text(
"Search your term",
style: TextStyle(fontSize: 20),
),
),
body: Container(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
onChanged: (query) {
//search is done here
// filterSearchResults(query);
},
decoration: InputDecoration(
labelText: 'Search',
hintText: 'Search your term',
suffixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(25.0),
),
),
),
),
),
Expanded(
child: FutureBuilder(
future: DefaultAssetBundle.of(context)
.loadString('assets/data.json'),
builder: (context, snapshot) {
var entries = json.decode(snapshot.data.toString());
final item = entries.where((e) => e['Entry'] == 'Accident'); //Accident will be changed with query
print(item);
print(entries);
return ListView.builder(
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
var entrada = entries[index];
//print(entrada);
return Container(
margin: EdgeInsets.symmetric(vertical: 2.0),
color: Colors.transparent,
width: MediaQuery.of(context).size.width,
height: 60,
child: RaisedButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Destination(
entry: entrada['Entry'],
definition: entrada['Definition'],
),
),
);
},
color: Colors.blue[900],
child: Text(
entrada['Entry'],
style: TextStyle(
color: Colors.white,
fontFamily: 'Raleway',
fontSize: 18.0,
),
),
),
);
},
itemCount: entries == null ? 0 : entries.length,
);
},
),
//child: searchedItems,
),
],
),
),
);
}
}
The issue that I am seeing is that the filtered result (item) is empty and it should contain the entry related to "Accident".
Could you give a hand for the implementation of this search functionality?
Thanks in advance
add .toList() to create new list
final item = entries.where((e) => e['Entry'] == 'Accident').toList();
Here is a stripped down code sample describing how to filter the items:
final List<Map<String, String>> items = [
{'Entry': 'Accident', 'Definition': 'Accident description.'},
{'Entry': 'Accident Insurance', 'Definition': 'Insurance description.'},
];
void main() {
final results = items.where((item) => item['Entry'] == 'Accident');
print(results);
// Iterable<Map<String, String>> ({Entry: Accident, Definition: An unexpected event or circumstance without deliberate intent.})
final result = results.first;
print(result);
// Map<String, String> {Entry: Accident, Definition: An unexpected event or circumstance without deliberate intent.}
}
Note that where returns an Iterable. You can use toList() to get a List of Maps.
Here is a Flutter sample application closer to what you did before:
import 'dart:convert';
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: MyWidget()));
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future:
DefaultAssetBundle.of(context).loadString('assets/entries.json'),
builder: (context, snapshot) {
final items = json.decode(snapshot.data.toString());
final result =
items.where((item) => item['Entry'] == 'Accident').first;
return Column(
children: [
Text('Accident Definition:'),
Text(result['Definition']),
],
);
},
),
);
}
}
The JSON File I used is here:
[
{
"Entry": "Accident",
"Definition": "Accident description."
},
{
"Entry": "Accident Insurance",
"Definition": "Insurance description."
}
]

How can i get the radio button data with controller in flutter?

I created a widget which is sending data via an API in json format, built with controllers such as ;
final quantNumberController = TextEditingController();
And i am getting value from controller ;
String quant = quantNumberController.text;
And i store the data in json format such as ;
var data = {'quant': quant}
My current text widget container structure is like ;
Container(
width: 280,
padding: EdgeInsets.all(10.0),
child: TextField(
controller: quantNumberController,
autocorrect: true,
decoration: InputDecoration(hintText: 'Enter location'),
)
),
I would like to get this data within radio button structure. Is it possible to get the data with controller like before i did, or how should i get the data to my result json file ?
I tried like this ;
Container(
margin: EdgeInsets.fromLTRB(0, 0, 0, 10),
child: Column(
children: <Widget>[
Text('Location'),
ListTile(
title: const Text('First value'),
leading: Radio(
value: Cap.Cap33,
groupValue: _capp,
onChanged: (Capp value) {
setState(() {
_capp = value;
capp = 'Cap33';
});
},
),
),
ListTile(
title: const Text('Second value'),
leading: Radio(
value: Capp.Cap22,
groupValue: _capp,
onChanged: (Capp value) {
setState(() {
_capp = value;
capp = 'Cap22';
});
},
),
),
ListTile(
title: const Text('Third value'),
leading: Radio(
value: Capp.Cap44,
groupValue: _capp,
onChanged: (Capp value) {
setState(() {
_capp = value;
capp = 'Cap44';
});
},
),
),
],
) ,
),
Thanks.
you can define a function that takes a controller
widget myRadioButton(TextEditingController quantNumberController ){
return Radio(
value:quantNumberController.text
groupValue: _capp,
onChanged: (Capp value) {
setState(() {
_capp = value;
capp = 'Cap33';
});}
for using
Container(
child:myRadioButton (quantNumberController:quantNumberController)
)
You can use a variable like "Location Value"
Syntax -
late String LocationValue = '';
before #override
Widget build(BuildContext context)
And then assign LocationValue on radio button on change attribute
onChanged: ((value) {
LocationValue = 'cap33';
setState(() {
_value = value!;
});
}),

How to render list inside list in flutter?

I'm creating an flutter app which should show list of teams, and each team is an object with items like
name: string
players: array of
name: string
so it looks like this
List teams = [
{
'name': 'Team one',
'players': [
{
'name': 'Team one player one',
},
{
'name': 'Team one player two',
},
{
'name': 'Team one player three',
},
]
},
{
'name': 'Team two',
'players': [
{
'name': 'Team two player one',
},
{
'name': 'Team two player one',
},
{
'name': 'Team two player three',
},
]
},
];
Further, in my code, I'm iterating through all teams with ListView, like this
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: renderTeams(teams),
),
);
}
and renderTeams() looks like this:
Widget renderTeams(List teams) {
return ListView.builder(
itemCount: teams.length,
itemBuilder: (context, index) {
return Padding(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.min,
children: [
Text(teams[index]['name']),
Row(
children: <Widget>[
Flexible(
child: PlayerCard(
player: teams[index]['players'][0],
),
),
Flexible(
child: PlayerCard(
player: teams[index]['players'][1],
),
),
Flexible(
child: PlayerCard(
player: teams[index]['players'][2],
),
),
],
)
],
),
);
},
);
}
This works well, everything gets rendered accordingly.
However, I'd like to, instead adding each player separately, iterate through each's team players, so my renderTeams() would look like this:
Widget renderTeams(List teams) {
return ListView.builder(
itemCount: teams.length,
itemBuilder: (context, index) {
return Padding(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.min,
children: [
Text(teams[index]['name']),
renderPlayers(teams[index]['players'])
],
),
);
},
);
}
and renderPlayers() looks like this:
renderPlayers(players) {
return Row(children: players.map((player) => {
Flexible(
child: PlayerCard(
player: player,
),
)
}).toList());
}
This is where my troubles begin, as I'm getting errors like
type 'List<dynamic>' is not a subtype of type 'List<Widget>'
And I've googled around, but other responses, tried to fix types, but that leads me into infinite loop of trying to fix errors i do not understand.
Anyone got any hint? Thanks in advance
Remove { }
renderPlayers(players) {
return Row(children: players.map((player) =>
Flexible(
child: PlayerCard(
player: player,
),
)
).toList());
}
Explanation
=> means return. => { ... } means returning a function (dynamic). That's why it was detected as List<dynamic>
Use Spread Operator [...]
The best solution for this type of problem is the Spreed Operator [...]. The spread operator combines two or more list instances. It also extends a collection's elements of a such as a list.
You can use it with Columns, Rows or Listview.
Like this:
// List
final variableValuesList = [
VariablesWithValues(
title: 'a',
value: 1,
),
VariablesWithValues(
title: 'b',
value: 1,
),
];
/// using inside column
Column(
children: [
///getting values from the list through spread operator
...variableValuesList.map((item) => Text(${item.title} = ${item.value})
).toList(),