Search bar with ListView possible in Flutter? - list

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

Related

Manage items in a List with their ids

Let me explain, I have two List Views with Items. At the moment I don’t give an id to these items but I have a problem. In fact, when I remove an item from my favorites list, it doesn’t change the icon (favorite or not favorite) for the right item on the home_screen.
I want to get the place of the item in the menu screen so I can change the icon from the favorites list. I’m using the provider package.
And so I wonder if it wouldn’t be better to create an id for each item and store a List<int> and then create a List<Item> in my favorites list. Also, I can use this id to change the right icon.
But I don’t know how to use these ids to create a List and then change the right icon.
Illustrations of what I said :
Black heart = in favorite and White heart = not in favorite.
It is the wrong item which is deleting.
My code on Github ans some relevant parts of my code :
favModel.dart
class FavModel extends ChangeNotifier {
List<Item> favList = [];
List<bool> isInFav = [];
addInFavorite(title, description, index){
Item item = Item(title: title, description: description, );
favList.add(item);
isInFav[index] = true;
notifyListeners();
}
removeOfFavorite(int index, int index2){
favList.removeAt(index);
isInFav[index2] = false;
notifyListeners();
}
implement(){
isInFav.add(false);
}
}
favorite_screen.dart
class Favorite extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Favorite'),
),
body: Consumer<FavModel>(
builder: (context, favModel, child) {
return ListView.builder(
itemCount: favModel.favList.length,
itemBuilder: (context, index) {
return TextObject(favModel.favList[index].title,
favModel.favList[index].description),
Padding(
padding: const EdgeInsets.all(7.0),
child: GestureDetector(
child: Icon(
Icons.favorite,
color: Colors.red,
size: 32,
),
onTap: () {
favModel.removeOfFavorite(index, index);
}),
),
});
},
),
);
}
}
home_screen.dart
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
actions: [
IconButton(
icon: Icon(Icons.favorite_border),
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
fullscreenDialog: true,
builder: (context) {
return Favorite();
},
),
),
),
],
),
body: Consumer<FavModel>(builder: (context, favModel, child) {
return ListView.builder(
shrinkWrap: false,
itemCount: itemData.length,
itemBuilder: (context, index) {
favModel.implement();
return TextObject(
itemData[index].title, itemData[index].description),
Padding(
padding: const EdgeInsets.all(7.0),
child: GestureDetector(
child: Icon(
favModel.isInFav.elementAt(index)
? Icons.favorite
: Icons.favorite_border,
color:
favModel.isInFav[index] ? Colors.red : null,
size: 32,
),
onTap: () {
favModel.isInFav[index]
? null
: Provider.of<FavModel>(context,
listen: false)
.addInFavorite(
itemData[index].title,
itemData[index].description,
index,
);
}),
);
});
}),
);
}
}
Where I want to get the index is in the favorite_screen.dart at this line favModel.removeOfFavorite(index, index);
I would suggest you to add bool isFavorite to your class Item and add an id for the class also. So you can avoid having two arrays.
And using the id will help you using some awesome methods like findWhere and removeWhere
EDIT
You can iterate the List using for
for(int i = 0;i<favList.length;i++){
if(favList[i].id == selectedItem.id){
favList[i].isSelected = true;
break;// break the loop no need to continue
}
}
notifyListeners()
Notice that now you have to pass Item instead of index

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

Flutter list of Text: How to fix the style of all list items

I am new to flutter and to the concept of Object orientation in general. I am building a list of Text to be used with a CupertinoPicker in flutter, I want to use the same style for all the list items but I don't want to keep repeating the lines and each time specifying the text style.
For example, see the list of car manufacturers below:
import 'package:flutter/material.dart';
TextStyle kStyle = TextStyle(color: Colors.white, fontWeight: FontWeight.w900);
List<Text> manufacturers = [
Text('Toyota', style: kStyle,),
Text('VolksWagen', style: kStyle,),
Text('Nissan', style: kStyle,),
Text('Renault', style: kStyle,),
Text('Mercedes', style: kStyle,),
Text('BMW', style: kStyle,)
];
You see the list items in manufacturers list can get so long with more cars, can I use a class to tell flutter that my style is fixed to kstyle for all the items without explicitly writing style: kstyle for every single line?
Basically We can use DefaultTextStyle widget
Final Result
CupertinoPicker Widget
Common Column Widget
1. The Problem is we need to use CupertinoPicker
which in the library, it is defined as
final Widget result = DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.pickerTextStyle,
child: Stack(
2. Solution : Override Theme
Therefore We are required to defined its style at the very beginning definition of our app
const TextStyle kStyle = TextStyle(
color: Colors.blue,
fontWeight: FontWeight.w900,
);
class FlutterApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Cupertino Picker',
home: ListViewScreen(),
theme: ThemeData(
cupertinoOverrideTheme: CupertinoThemeData( // <---------- this
textTheme: CupertinoTextThemeData(
pickerTextStyle: kStyle,
),
),
),
);
}
}
A. Full Working Code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(FlutterApp());
}
const TextStyle kStyle = TextStyle(
color: Colors.blue,
fontWeight: FontWeight.w900,
);
class FlutterApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Cupertino Picker',
home: ListViewScreen(),
theme: ThemeData(
cupertinoOverrideTheme: CupertinoThemeData( // <---------- this
textTheme: CupertinoTextThemeData(
pickerTextStyle: kStyle,
),
),
),
);
}
}
class ListViewScreen extends StatelessWidget {
final List<Text> manufacturers = [
Text('Toyota'),
Text('VolksWagen'),
Text('Nissan'),
Text('Renault'),
Text('Mercedes'),
Text('BMW')
];
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text("Select Car"),
),
child: Container(
height: 200,
child: CupertinoPicker(
itemExtent: 50,
onSelectedItemChanged: (int index) {
print(index);
},
children: manufacturers,
),
),
);
}
}
B. [Optional] Simple use of Default Text Style
List<Text> manufacturers = [
Text('Toyota'),
Text('VolksWagen'),
Text('Nissan'),
Text('Renault'),
Text('Mercedes'),
Text('BMW')
];
const TextStyle kStyle = TextStyle(
color: Colors.white,
fontWeight: FontWeight.w900,
);
class CarList extends StatelessWidget {
#override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: kStyle,
child: Column(
children: manufacturers,
),
);
}
}
You can create a new widget:
class MyTextWidget extends StatelessWidget {
final String text;
const MyTextWidget({Key key, this.text}) : super(key: key);
#override
Widget build(BuildContext context) {
return Text(text,style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900),);
}
}
and use it in your list
List<Text> manufacturers = [
MyTextWidget('Toyota'),
MyTextWidget('VolksWagen'),
MyTextWidget('Nissan'),
MyTextWidget('Renault'),
MyTextWidget('Mercedes'),
MyTextWidget('BMW')
];
If you want to change the font in all the application, you must change it from MaterialApp like this:
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
textTheme: TextTheme(
//Use the appropriate TextStyle
),
),);
}
You can create one method for all Text widgets:
Text styledText(String text) => Text(text, style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900));
and use it in your list:
List<Text> manufacturers = [
styledText('Toyota'),
styledText('VolksWagen'),
styledText('Nissan'),
styledText('Renault'),
styledText('Mercedes'),
styledText('BMW')
];
You can also create a list of strings
List<String> manufacturers = [
'Toyota',
'VolksWagen',
'Nissan',
'Renault',
'Mercedes',
'BMW',
];
And use tis method when you iterate through your list.
Or you can create a class instead of the method:
class CustomStyledText extends StatelessWidget {
final String text;
const CustomStyledText(this.text, {Key key}) : super(key: key);
TextStyle get _style => TextStyle(color: Colors.white, fontWeight: FontWeight.w900);
#override
Widget build(BuildContext context) => Text(text, style: _style);
}
You can create an extension on the Text widget and use that:
Create an extension:
// extension
extension on Text {
// method to apply style
applyStyle(TextStyle textStyle) {
return Text(
this.data,
style: textStyle,
);
}
}
Use the extension method on the Text widget:
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
...List.generate(
manufacturers.length,
// call the applyStyle method on the Text widget
(index) => manufacturers[index].applyStyle(kStyle),
).toList(),
],
),
);

Flutter, How to get Image URL from Firestore for respective Index Items and show in a list View

I am trying to create an app which displays a dynamic FireStore List. I have made the List with a Future Builder, what I am trying to achieve is to add a Icon to every list of which the URL should be fetched from firesotre of the same documents Index. For Eg. Flipkart is a Document in FireStore it has a "images" field with the URL to Flipkart logo. I want the List View "leading" property to display this image by getting the URL from FireStore Database.
ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
return Card(
margin: EdgeInsets.fromLTRB(10, 2, 10, 2),
elevation: 3,
borderOnForeground: true,
child: ListTile(
title: Text(snapshot.data[index].data['title']),
subtitle: Text(snapshot.data[index].data['description']),
onTap: () => navigateToDetails(snapshot.data[index]),
),
);
});
The Code would go something like
ListTile(
leading: "Code Goes Here"
title: Text(snapshot.data[index].data['title']),
subtitle: Text(snapshot.data[index].data['description']),
Please share your valuable thoughts. I would like this to work, New to programming.
Full Code For FireStore Get Data:
class OfferScroll extends StatefulWidget {
#override
_OfferScrollState createState() => _OfferScrollState();
}
class _OfferScrollState extends State<OfferScroll> {
Future _data;
Future getOffers() async {
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore.collection('Offers').getDocuments();
return qn.documents;
}
navigateToDetails (DocumentSnapshot offers) {
Navigator.push(context, MaterialPageRoute(builder: (context) =>
OfferDetails(offers: offers,)));
}
#override
void initState() {
super.initState();
_data = getOffers();
}
#override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: _data,
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: AwesomeLoader(
loaderType: AwesomeLoader.AwesomeLoader3,
color: Colors.green[900],
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
return Card(
margin: EdgeInsets.fromLTRB(10, 2, 10, 2),
elevation: 3,
borderOnForeground: true,
child: ListTile(
title: Text(snapshot.data[index].data['title']),
subtitle: Text(snapshot.data[index].data['description']),
onTap: () => navigateToDetails(snapshot.data[index]),
),
);
});
}
}),
);
}
}
When you have the URL as a string in your FireStore you can retrieve the URL with someone like this: snapshot.data[index].data['imageFieldName'] and then you can give the return of this (the URL) to a NetworkImage to display the image.

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.