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

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!;
});
}),

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

Quicker way to implement into a list?

Im making a list of radio buttons. But cant figure a way to map them. The current method making one by one which is too much and with 10+ radio buttons this is taking up hundreds of lines of code.
enum SingingCharacter {char1, char2, char3, char4}
class _HomeScreenState extends State<HomeScreen> {
SingingCharacter _character = SingingCharacter.char1;
final List myList= ['One','Two','Thre' ];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Container(
child: Column(children: <Widget>[
RadioListTile<SingingCharacter>(
title: Text('${myList[0]}'),
value: SingingCharacter.char1,
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
),
RadioListTile<SingingCharacter>(
title: Text('${myList[1]}'),
value: SingingCharacter.char2,
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
)
....
]),
));
}
}
Any method to loop through this and show in children?
Thanks
You could change your List to a Map and then use this to map your enum values to Widgets. Like this (disclaimer: Code not tested, but something like this should be possible):
enum SingingCharacter {char1, char2, char3}
class _HomeScreenState extends State<HomeScreen> {
SingingCharacter _character = SingingCharacter.char1;
final Map<SingingCharacter, String> radioMap = {SingingCharacter.char1: 'One', SingingCharacter.char2: 'Two', SingingCharacter.char3: 'Three'};
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Container(
child: Column(
children: _generateRadioButtons()
),
)
);
}
List<Widget> _generateRadioButtons() {
return SingingCharacter.values.map((char) {
return RadioListTile<SingingCharacter>(
title: Text('${radioMap[char]}'),
value: char
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
);
}).toList();
}
}
You can take advantage of the spread operator and unwrap directly a for loop on your Column.
final List myList= ['One','Two','Thre' ];
return Column(children: [
for (int i = 0; i < myList.length; i++)
RadioListTile<SingingCharacter>(
title: Text(myList[i]),
value: SingingCharacter.values[i],
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
),
]);

Create a switch list tile with separators in flutter

I am trying to create a list of switch tiles in flutter which have separators between the tiles.
I've tried doing this by using ListTile.divideTiles:
ListView(
children: ListTile.divideTiles(
context: context,
tiles: [
SwitchListTile(
secondary: Icon(Icons.signal_cellular_4_bar),
title: Text(
"First Tile",
),
value: var1,
onChanged: (bool value) {
setState(
() {
var1= value;
},
);
},
),
SwitchListTile(
secondary: Icon(Icons.swap_vert),
title: Text(
"Second Tile",
),
value: var2,
onChanged: (bool value) {
setState(
() {
var2= value;
},
);
},
),
],
),
),
But when I tried running the code I got the following error:
"type '_SyncIterable<Widget>' is not a subtype of type 'List<Widget>'"
Who do I create a list of switch tiles with separator?
Please try this.
Add .toList() to the end of your ListTile.divideTiles
ListTile.divideTiles(
// all your code
// all your code
// all your code
).toList()
Why don't you try ListView.separated ?
int _selectedIndex = 0;
return ListView.separated(
//Here's your separator
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 10, //Whatever spacing you want.
);
},
physics: BouncingScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: 2, //How many tiles you want
padding: EdgeInsets.all(10),
itemBuilder: (BuildContext context, int index) {
return ClipRRect( //round up the edges for nicer look
borderRadius: BorderRadius.all(Radius.circular(5)),
//And here's your tile
child: SwitchListTile(
tileColor: Colors.grey[900],
selectedTileColor: Colors.black,
selected: index == _selectedIndex,
value: ... ,
onChanged: (v) {
...
},
title: Text('Tile #' + index.toString()),
subtitle: Text('-'),
),
);
},
);

Search bar with ListView possible in Flutter?

I want to implement a searchbar in my flutter application. I have to go through a listview out of ListTiles. Here I want to check if the title of the listtile contains the letters in the search field. Is this possible with a List?
It does not have to be with the title. It could be something else with what I can identify the Tile. But please, not the index, the user would not know it.
Is a List the right widget or do I have to use something else to implement a search Engine in my Application
Rather than using a 3rd party package, you can use native showSearch() function :
showSearch(context: context, delegate: ListSearchDelegate());
And then a class extending SearchDelegate:
class ListSearchDelegate extends SearchDelegate{
ListSearchDelegate({Key key,}): super() ;
List<String> listItems = <String>['One', 'Two', 'Three', 'Four', 'Five'] ;
#override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = '';
},
),
];
}
#override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
close(context, null);
},
);
}
#override
Widget buildResults(BuildContext context) {
List<String> subList ;
subList = query != '' ? listItems.where((item) => item.contains(query)).toList() :
listItems ;
return ListView.builder(
itemCount: subList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(subList[index]),
);
}
);
}
#override
Widget buildSuggestions(BuildContext context) {
return Container();
}
}
Try https://pub.dev/packages/flutter_search_panel
List<SearchItem<int>> data = [
SearchItem(0, 'This'),
SearchItem(1, 'is'),
SearchItem(2, 'a'),
SearchItem(3, 'test'),
SearchItem(4, '.'),
];
FlutterSearchPanel<int>(
padding: EdgeInsets.all(10.0),
selected: 3,
title: 'Demo Search Page',
data: data,
icon: new Icon(Icons.check_circle, color: Colors.white),
color: Colors.blue,
textStyle: new TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20.0, decorationStyle: TextDecorationStyle.dotted),
onChanged: (int value) {
print(value);
},
),

Flutter return Firestore array values to a List

I am using Flutter table calendar plugin to make a calendar. In order to put events into the calendar, I have to add data to _events map. I want to get the data from Firestore document, and put the data into _events map. However, I don't know how to do it. I search everywhere but I can't get an answer.
This is my code
class _MemberEventsState extends State<MemberEvents>
with TickerProviderStateMixin {
Map<DateTime, List> _events;
List _selectedEvents;
AnimationController _animationController;
CalendarController _calendarController;
List<String> list = List();
#override
void initState() {
super.initState();
final _selectedDay = DateTime.now();
Firestore.instance
.collection('events')
.document('2019-07-30')
.get()
.then((DocumentSnapshot ds) {
list = List.from(ds['title']);
});
_events = {DateTime.parse("2019-08-01"): list};
_selectedEvents = _events[_selectedDay] ?? [];
_calendarController = CalendarController();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
_animationController.forward();
}
#override
void dispose() {
_animationController.dispose();
_calendarController.dispose();
super.dispose();
}
void _onDaySelected(DateTime day, List events) {
print('CALLBACK: _onDaySelected');
setState(() {
_selectedEvents = events;
});
}
void _onVisibleDaysChanged(
DateTime first, DateTime last, CalendarFormat format) {
print('CALLBACK: _onVisibleDaysChanged');
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
_buildTableCalendar(),
const SizedBox(height: 8.0),
const SizedBox(height: 8.0),
Expanded(child: _buildEventList()),
],
),
);
}
Widget _buildTableCalendar() {
return TableCalendar(
calendarController: _calendarController,
events: _events,
startingDayOfWeek: StartingDayOfWeek.sunday,
calendarStyle: CalendarStyle(
selectedColor: Colors.deepOrange[400],
todayColor: Colors.blueAccent[200],
markersColor: Colors.brown[700],
outsideDaysVisible: false,
),
headerStyle: HeaderStyle(
formatButtonTextStyle:
TextStyle().copyWith(color: Colors.white, fontSize: 15.0),
formatButtonDecoration: BoxDecoration(
color: Colors.deepOrange[400],
borderRadius: BorderRadius.circular(16.0),
),
),
onDaySelected: _onDaySelected,
onVisibleDaysChanged: _onVisibleDaysChanged,
);
}
Widget _buildEventList() {
return ListView(
children: _selectedEvents
.map((event) => Container(
decoration: BoxDecoration(
border: Border.all(width: 0.8),
borderRadius: BorderRadius.circular(12.0),
),
margin:
const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
child: ListTile(
title: Text(event.toString()),
),
))
.toList(),
);
}
}
So in the first step to achieve my goal, I made a document named 2019-07-30, then I made an array in it named title. Then I tried to get the values in the array to a List named list. However, list returned null.
I don't know where I went wrong.
I am new to Flutter, so the question might seem stupid.
Also, I am new to stackoverflow, so if I did any steps wrong on describing the question, please tell me so I can fix it.