I am trying to use Flutter tagging and planning to get and save to database.
I am using Flutter Tagging plugin. Here is the example which i am trying to replicate.
https://fluttercore.com/flutter-tagging-input-widget/
class Tagging extends StatefulWidget {
#override
_TaggingState createState() => _TaggingState();
}
class _TaggingState extends State<Tagging> {
final _scaffoldKey = GlobalKey<ScaffoldState>();
String _selectedValuesJson = 'Nothing to show';
List searchlists = [];
var dtguid;
var dtgname;
int count = 0;
var offset = 0;
String nodata;
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
String text = "Nothing to show";
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
// title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: FlutterTagging(
textFieldDecoration: InputDecoration(
border: OutlineInputBorder(),
hintText: "Tags",
labelText: "Enter tags"),
addButtonWidget: _buildAddButton(),
chipsColor: Colors.pinkAccent,
chipsFontColor: Colors.white,
deleteIcon: Icon(Icons.cancel,color: Colors.white),
chipsPadding: EdgeInsets.all(2.0),
chipsFontSize: 14.0,
chipsSpacing: 5.0,
chipsFontFamily: 'helvetica_neue_light',
suggestionsCallback: (pattern) async {
return await TagSearchService.getSuggestions(pattern);
},
onChanged: (result) {
setState(() {
text = result.toString();
});
},
),
),
SizedBox(
height: 20.0,
),
Center(
child: Text(
text,
style: TextStyle(color: Colors.pink),
),
)
],
),
),
);
}
Widget _buildAddButton() {
return Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
color: Colors.pinkAccent,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Icon(
Icons.add,
color: Colors.white,
size: 15.0,
),
Text(
"Add New Tag",
style: TextStyle(color: Colors.white, fontSize: 14.0),
),
],
),
);
}
}
class TagSearchService {
static Future<List> getSuggestions(String query) async {
await Future.delayed(Duration(milliseconds: 400), null);
List<dynamic> tagList = <dynamic>[];
tagList.add({'name': "Flutter", 'value': 1});
tagList.add({'name': "HummingBird", 'value': 2});
tagList.add({'name': "Dart", 'value': 3});
List<dynamic> filteredTagList = <dynamic>[];
if (query.isNotEmpty) {
filteredTagList.add({'name': query, 'value': 0});
}
for (var tag in tagList) {
if (tag['name'].toLowerCase().contains(query)) {
filteredTagList.add(tag);
}
}
return filteredTagList;
}
}
For some reason it is giving error at below code.
FlutterTagging(
textFieldDecoration: InputDecoration(
border: OutlineInputBorder(),
hintText: "Tags",
labelText: "Enter tags"),
addButtonWidget: _buildAddButton(),
chipsColor: Colors.pinkAccent,
chipsFontColor: Colors.white,
deleteIcon: Icon(Icons.cancel,color: Colors.white),
chipsPadding: EdgeInsets.all(2.0),
chipsFontSize: 14.0,
chipsSpacing: 5.0,
chipsFontFamily: 'helvetica_neue_light',
suggestionsCallback: (pattern) async {
return await TagSearchService.getSuggestions(pattern);
},
onChanged: (result) {
Here is the picture.
I am using this version.
flutter_tagging: ^2.2.0+3
You can copy paste run full code below
Your code use flutter_tagging version 1.0.0, you can set in pubspec.yaml
Syntax error will disappear after set version
dependencies:
flutter:
sdk: flutter
flutter_tagging: 1.0.0
for latest version 2.2.0+3, you can directly use https://github.com/sarbagyastha/flutter_tagging/tree/master/example
working demo for version 1.0.0
full code
import 'package:flutter/material.dart';
import 'package:flutter_tagging/flutter_tagging.dart';
class Tagging extends StatefulWidget {
#override
_TaggingState createState() => _TaggingState();
}
class _TaggingState extends State<Tagging> {
final _scaffoldKey = GlobalKey<ScaffoldState>();
String _selectedValuesJson = 'Nothing to show';
List searchlists = [];
var dtguid;
var dtgname;
int count = 0;
var offset = 0;
String nodata;
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
String text = "Nothing to show";
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
// title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: FlutterTagging(
textFieldDecoration: InputDecoration(
border: OutlineInputBorder(),
hintText: "Tags",
labelText: "Enter tags"),
addButtonWidget: _buildAddButton(),
chipsColor: Colors.pinkAccent,
chipsFontColor: Colors.white,
deleteIcon: Icon(Icons.cancel, color: Colors.white),
chipsPadding: EdgeInsets.all(2.0),
chipsFontSize: 14.0,
chipsSpacing: 5.0,
chipsFontFamily: 'helvetica_neue_light',
suggestionsCallback: (pattern) async {
return await TagSearchService.getSuggestions(pattern);
},
onChanged: (result) {
setState(() {
text = result.toString();
});
},
),
),
SizedBox(
height: 20.0,
),
Center(
child: Text(
text,
style: TextStyle(color: Colors.pink),
),
)
],
),
),
);
}
Widget _buildAddButton() {
return Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
color: Colors.pinkAccent,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Icon(
Icons.add,
color: Colors.white,
size: 15.0,
),
Text(
"Add New Tag",
style: TextStyle(color: Colors.white, fontSize: 14.0),
),
],
),
);
}
}
class TagSearchService {
static Future<List> getSuggestions(String query) async {
await Future.delayed(Duration(milliseconds: 400), null);
List<dynamic> tagList = <dynamic>[];
tagList.add({'name': "Flutter", 'value': 1});
tagList.add({'name': "HummingBird", 'value': 2});
tagList.add({'name': "Dart", 'value': 3});
List<dynamic> filteredTagList = <dynamic>[];
if (query.isNotEmpty) {
filteredTagList.add({'name': query, 'value': 0});
}
for (var tag in tagList) {
if (tag['name'].toLowerCase().contains(query)) {
filteredTagList.add(tag);
}
}
return filteredTagList;
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Tagging(),
);
}
}
Related
I am new to flutter. I have a task to create a local repository for a task list. I tried many options to write the code but none of them worked. I read and watched a lot of videos and articles. Please write your options how I can record it
Here is my code:
import 'dart:convert';
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Home extends StatefulWidget {
const Home ({key}): super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
final myController = TextEditingController();
bool submit = false;
Color mainColor = Color(0xFFEEEFF5);
Color secColor = Color(0xFF3A3A3A);
Color tdBlue = Color(0xFF5F52EE);
String temp = "";
List todoList = [];
#override
void initState() {
super.initState();
myController.addListener(() {
setState(() {
submit = myController.text.isNotEmpty;
});
});
todoList.addAll(['Biy milk','Dishhh Wash','Придбати картоплю', 'Buy cucumbers', 'Kylunuch'],);
}
#override
void dispose() {
// Clean up the controller when the widget is disposed.
myController.dispose();
super.dispose();
}
void clearText() {
myController.clear();
}
#override
Widget build(BuildContext context){
return Scaffold(
backgroundColor: mainColor,
appBar: AppBar(
elevation: 0.0,
backgroundColor: secColor,
title: Text ('ToDo - List', style: TextStyle(fontSize: 26.5, fontWeight: FontWeight.bold, fontStyle: FontStyle.italic),),
),
body: Column(
children: [
Container(
margin: EdgeInsets.only(
top: 15.0,
left: 13.0,
right: 8.0,
),
child: Row(
children: [
Expanded(
child: TextField(
onChanged: (String value) {
temp = value;
},
controller: myController,
decoration:
InputDecoration(
prefixIcon: Icon(Icons.notes, color: Colors.orangeAccent,),
labelText: 'Замітка',
hintText: 'Введіть замітку',
filled: true,
fillColor: Colors.white,
border: OutlineInputBorder(),
contentPadding: EdgeInsets.all(10.0),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(30.0),),
),
),
),
),
SizedBox(
width: 10.0,
),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: tdBlue),
onPressed:
submit ? () => submitData() : null,
child:
Text('+', style: TextStyle(fontSize: 35),),
),
], // Закривається 2-ий чілдрен
), //Row 1-ий
),
Expanded(
child: Padding(
padding: EdgeInsets.only(
top: 15.0,
),
child: ListView.builder(
itemCount: todoList.length,
itemBuilder: (BuildContext context, int index){
return Dismissible(
key: Key(todoList[index]),
child: Card(
margin: EdgeInsets.only(
top: 16.0,
left: 25.0,
right: 25.0,
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25.0)),
elevation: 0.0,
child:
ListTile(
leading: Icon(Icons.delete_sweep, color: Colors.orangeAccent,),
title: Text(todoList[index],
),),
),
onDismissed: (direction){
if (direction == DismissDirection.endToStart) {
setState(() {
todoList.removeAt(index);
});// Закривається Сетстейт (")") і }
}
}, // Закривається ОнДісмісед
);
},
),
)
),
], // Закривається 1-ий чілдрен
),
);
}
submitData() {
setState(() {
todoList.add(temp);
clearText();
});
} // submit data
}
I tried many options to write the code but none of them worked.
Try this
List<String> todoList = [];
#override
void initState() {
super.initState();
myController.addListener(() {
setState(() {
submit = myController.text.isNotEmpty;
});
});
omLoadData();
}
submitData() async {
setState(() {
todoList.add(temp);
clearText();
});
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setStringList('todo_list', todoList);
}
omLoadData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final data = prefs.getStringList("todo_list");
todoList.addAll(data!);
}
I am developing a task book, most of the tasks I have implemented but there is one that I can't solve, when I add a task it is added to the end of the list, and I want it to be at the top of the list. And also there is a problem when the theme changes, I want that if the theme is black, the text "Tasks +" were white and vice versa. Here is my code:
import 'package:flutter/material.dart';
void main(){
runApp(MaterialApp(
home: App(),
));
}
class ListItem{
String todoText;
bool todoCheck;
ListItem(this.todoText, this.todoCheck);
}
class _strikeThrough extends StatelessWidget{
final String todoText;
final bool todoCheck;
_strikeThrough(this.todoText, this.todoCheck) : super();
Widget _widget(){
if(todoCheck){
return Text(
todoText,
style: TextStyle(
fontSize: 22.0,
),
);
}
else{
return Text(
todoText,
style: TextStyle(
fontSize: 22.0
),
);
}
}
#override
Widget build(BuildContext context){
return _widget();
}
}
const Color ColorTextW = Colors.black;
class App extends StatefulWidget{
#override
AppState createState(){
return AppState();
}
}
final ValueNotifier<ThemeMode> _notifier = ValueNotifier(ThemeMode.light);
late Color ColorType = Colors.black;
class AppState extends State<App> {
bool valText = true;
var counter = 0;
var IconsType = Icons.wb_sunny ;
late Color ColorType = Colors.black;
var textController = TextEditingController();
var popUpTextController = TextEditingController();
List<ListItem> WidgetList = [];
#override
void dispose() {
textController.dispose();
popUpTextController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return ValueListenableBuilder<ThemeMode>(
valueListenable: _notifier,
builder: (_, mode, __) {
return MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: mode, // Decides which theme to show, light or dark.
home: Scaffold(
appBar: AppBar(
title: Text("Список задач"),
actions: <Widget>[
IconButton(
icon: Icon(IconsType,color : ColorType
),
onPressed:() =>
{
if (_notifier.value == ThemeMode.light) {
_notifier.value = ThemeMode.dark,
IconsType = Icons.dark_mode,
ColorType = Colors.white,
} else
{
_notifier.value = ThemeMode.light,
IconsType = Icons.wb_sunny,
ColorType = Colors.black,
}
}
)
],
//backgroundColor: Colors.orange[500],
iconTheme: IconThemeData(
color: Colors.white
),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
"Tasks",
style: TextStyle(
fontSize: 70.0,
fontWeight: FontWeight.bold,
color: ColorTextW,
),
),
IconButton(
color: Colors.black,
iconSize: 70,
constraints: const BoxConstraints(),
padding: EdgeInsets.fromLTRB(30.0, 10.0, 30, 10.0),
icon: const Icon(Icons.add_outlined),
onPressed: () {
if (textController.text.replaceAll(" ", "").isNotEmpty) {
WidgetList.add(
new ListItem(textController.text.replaceAll(" ", ""), false));
setState(() {
valText = true;
textController.clear();
});
}
else
{
setState(() {
valText = false;
});
}
},
)
],
),
),
Container(
width: MediaQuery
.of(context)
.size
.height * 0.45,
child: TextField(
style: TextStyle(
fontSize: 22.0,
//color: Theme.of(context).accentColor,
),
controller: textController,
cursorWidth: 5.0,
autocorrect: true,
autofocus: true,
//onSubmitted: ,
),
),
Align(
child:
(valText == false) ?
Align(child: Text(("Задача пустая"),
style: TextStyle(
fontSize: 25.0, color: Colors.red)),
alignment: Alignment.center) :
Align(child: Text((""),),
alignment: Alignment.center)),
Expanded(
child: ReorderableListView(
children: <Widget>[
for(final widget in WidgetList)
GestureDetector(
key: Key(widget.todoText),
child: Dismissible(
key: Key(widget.todoText),
child: CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
//key: ValueKey("Checkboxtile $widget"),
value: widget.todoCheck,
title: _strikeThrough(
widget.todoText, widget.todoCheck),
onChanged: (checkValue) {
//_strikethrough toggle
setState(() {
if (!checkValue!) {
widget.todoCheck = false;
}
else {
widget.todoCheck = true;
}
});
},
),
background: Container(
child: Icon(Icons.delete),
alignment: Alignment.centerRight,
color: Colors.redAccent,
),
direction: DismissDirection.endToStart,
movementDuration: const Duration(
milliseconds: 200),
onDismissed: (dismissDirection) { //Delete Todo
WidgetList.remove(widget);
},
),
)
],
onReorder: (oldIndex, newIndex) {
setState(() {
if (newIndex > oldIndex) {
newIndex -= 1;
}
var replaceWiget = WidgetList.removeAt(oldIndex);
WidgetList.insert(newIndex, replaceWiget);
});
},
),
)
],
),
)
);
}
);
}
}
In the onPressed method of your Add-IconButton do the following:
WidgetList.insert(0, new ListItem(textController.text.replaceAll(" ", ""), false));
This will insert the new item at the top of the existing list ^^
Can anyone please tell me how do I select multiple options in checkboxlisttile.
Here I am able to click only one option. I want to set the status column in note table in database as completed when i check the particular item.
(Actually I want to select the item as completed and display it under another tab called completed. checkboxlisttile is created dynamically i.e from database. When a new note is added it is displayed in this listview.)
note_info.dart //this is the screen where notes are displayed i.e listview
import 'dart:io';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/db_helper.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'new_note.dart';
class Note_Info extends StatefulWidget{
final String appBarTitle;
final CustomerModel customer;
//Note_Info();
Note_Info(this. customer, this.appBarTitle);
#override
State<StatefulWidget> createState() {
//return Note_InfoState();
return Note_InfoState(this. customer,this.appBarTitle);
}
}
class Note_InfoState extends State<Note_Info> {
DBService dbService = DBService();
List<NoteModel> noteList;
int count = 0;
static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
NoteModel note=NoteModel();
String appBarTitle;
CustomerModel customer=new CustomerModel();
Note_InfoState(this.customer, this.appBarTitle);
bool rememberMe = false;
DateTime _date = DateTime.now();
TextEditingController custfNameController = TextEditingController();
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
updateListView();
if (noteList == null) {
noteList = List<NoteModel>();
updateListView();
}
TextStyle titleStyle = Theme.of(context).textTheme.subhead;
var height = MediaQuery.of(context).size.height;
var name=customer.first_name+" "+customer.last_name;
custfNameController.text = name;
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(
Icons.add,
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => NewNote(customer,note)));
},
)
],
),
body: Container(
child: Column(
children: <Widget>[
TextField(controller: custfNameController,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
Padding(
padding: const EdgeInsets.all(15.0),
child: Row(children: [
ImageProfile(customer.cust_photo),
Padding(
padding: const EdgeInsets.only(left: 30.0),
child: IconButton(
icon: Icon(
Icons.call,
color: Colors.green,
size: 45,
),
onPressed: () {
},
),
),
],),
),
SizedBox(
height: 50,
child: AppBar(
bottom: TabBar(
tabs: [
Tab(
text: "All",
),
Tab(
text: "Pending",
),
Tab(
text: "Cancelled",
),
Tab(
text: "Completed",
),
],
),
),
),
// create widgets for each tab bar here
Expanded(
child: TabBarView(
children: [
// first tab bar view widget
Container(
child: getNotecheckList()
),
// second tab bar view widget
Container(
),
Container(
child: Center(
child: Text(
'Cancelled',
),
),
),
Container(
child: Center(
child: Text(
'Completed',
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 55.0,
width: 200,
child: RaisedButton(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Theme
.of(context)
.primaryColorDark,
textColor: Colors.white,
child: Text('Save', textScaleFactor: 1.5,),
onPressed: () {
setState(() {
//_reset();
});
},
),
),
),
]
),
)
));
}
Widget ImageProfile(String fileName) {
return Center(
child: CircleAvatar(
radius: 80.0,
backgroundImage: fileName == null
?AssetImage('images/person_icon.jpg')
:FileImage(File(customer.cust_photo))),
);
}
Future<void> updateListView() {
final Future<Database> dbFuture = DB.init();
dbFuture.then((database) {
int cid=customer.cust_id;
Future<List<NoteModel>> noteListFuture = dbService.getCustomerNotes(cid);
noteListFuture.then((noteList) {
setState(() {
this.noteList = noteList;
this.count = noteList.length;
});
});
});
}
int _isChecked=-1;
ListView getNotecheckList() {
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int position) {
return Card(
color: Colors.white,
elevation: 2.0,
child: CheckboxListTile(
title: Text(this.noteList[position].note),
subtitle: Text(this.noteList[position].actn_on),
//secondary: const Icon(Icons.web),
value: position== _isChecked,
onChanged: (bool value) {
setState(() {
_isChecked = value?position:-1;
});
},
controlAffinity: ListTileControlAffinity.leading,
),
);
},
);
}
}
new_note.dart //this is where new note is added.
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';
import 'package:intl/intl.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/form_helper.dart';
class NewNote extends StatefulWidget{
final NoteModel note;
final CustomerModel customer;
NewNote(this.customer,this. note);
//Dropdown
/*
final String label;
final Function(Color) onChanged;
final double height;
final double width;
NewNote.fordropdwn({
Key key,
this.onChanged,
this.height = 25,
this.width = 150,
this.label,
}) : super(key: key);*/
#override
State<StatefulWidget> createState() {
//return New_NoteState(this.customer);
return New_NoteState(this.customer,this.note);
}
}
class New_NoteState extends State<NewNote> with SingleTickerProviderStateMixin{
New_NoteState(this.customer,this.note);
NoteModel note=new NoteModel();
CustomerModel customer=new CustomerModel();
TextEditingController NoteController=TextEditingController();
TextEditingController custfNameController = TextEditingController();
DateTime _reminderDate = DateTime.now();
DBService dbService=new DBService();
SpeedDial _speedDial(){
return SpeedDial(
// child: Icon(Icons.add),
animatedIcon: AnimatedIcons.add_event,
animatedIconTheme: IconThemeData(size: 24.0),
backgroundColor: Colors.yellow,
curve: Curves.easeInCirc,
children: [
SpeedDialChild(
child: Icon(Icons.location_on,color: Colors.yellow,),
//backgroundColor: Theme.of(context).primaryColor,
label: 'Add Location',
//labelBackgroundColor:Theme.of(context).primaryColor,
),
SpeedDialChild(
child: Icon(Icons.keyboard_voice),
//backgroundColor: Colors.yellow,
label: 'Add voice',
//labelBackgroundColor: Colors.yellow
),
SpeedDialChild(
child: Icon(Icons.attachment_outlined,color :Colors.redAccent),
//backgroundColor:Theme.of(context).primaryColorLight,
label: 'Add File',
// labelBackgroundColor: Theme.of(context).primaryColorLight
),
SpeedDialChild(
child: Icon(Icons.image,color: Colors.lightBlue,),
//backgroundColor: Colors.yellow,
label: 'Add Image',
// labelBackgroundColor: Colors.yellow,
),
],
);
}
//for DropDownMenu
Color value=Colors.red;
final List<Color> colors = [
Colors.red,
Colors.blue,
Colors.green,
Colors.yellow,
Colors.pink,
Colors.purple,
Colors.brown,
];
//for Switch
bool isSwitched = false;
var textValue = 'Switch is OFF';
void toggleSwitch(bool value) {
if(isSwitched == false)
{
setState(() {
isSwitched = true;
note.rmnd_ind=1;
//this.note.remindOn = _reminderDate.toString();
});
}
else
{
setState(() {
isSwitched = false;
note.rmnd_ind=0;
});
}
}
#override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
var name=customer.first_name+customer.last_name;
custfNameController.text = name;
return WillPopScope(
onWillPop: () {
// Write some code to control things, when user press Back navigation button in device navigationBar
moveToLastScreen();
},
child: Scaffold(
appBar:AppBar(),
body:ListView(
children: <Widget>[
SizedBox(
height: 2.0,
),
TextField(controller: custfNameController,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
Align(
alignment: Alignment.centerLeft,
child: Text("Add New",textAlign: TextAlign.left,
style: TextStyle(fontSize: 22,fontWeight: FontWeight.bold),),
),
SizedBox(
height: 2.0,
),
Divider(),
SizedBox(
height: 2.0,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: NoteController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: const BorderSide(width: 2.0),)),
keyboardType: TextInputType.multiline,
minLines: 5,//Normal textInputField will be displayed
maxLines: 5, // when user presses enter it will adapt to it
onChanged: (value) {
this.note.note = value;
},
),
),
TableCalendar(
selectedDayPredicate: (day) {
return isSameDay(_reminderDate, day);
},
onDaySelected: (selectedDay, focusedDay) {
setState(() {
String _reminderDate = DateFormat('dd-MM-yyyy').format(selectedDay);
note.actn_on=_reminderDate.toString();
});
},// Set initial date
focusedDay: DateTime.now(),
firstDay: DateTime.utc(2010, 10, 16),
lastDay: DateTime.utc(2030, 3, 14),),
SizedBox(
height: height*0.03,
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(//mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Remind me",style: TextStyle(fontSize: 20),),
Padding(
padding: const EdgeInsets.only(left:80.0),
child: Container(
child: Switch(
onChanged: toggleSwitch,
value: isSwitched,
//activeColor: Colors.blue,
//activeTrackColor: Colors.yellow,
//inactiveThumbColor: Colors.redAccent,
//inactiveTrackColor: Colors.orange,
),
),
),
],),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(mainAxisAlignment: MainAxisAlignment.start,
children:<Widget>[
Text("Priority",style: TextStyle(fontSize: 20.0),),
Padding(
padding: const EdgeInsets.only(left:20.0),
child: Container(
child: SmoothStarRating(
size: height=50.0,
allowHalfRating: false,
onRated: (value) {
this.note.prty=value;
print("rating value -> $value");
},
),
),
)]),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Color",style: TextStyle(fontSize: 20),),
Padding(
padding: const EdgeInsets.only(left:80.0),
child: Container(
child: DropdownButton<Color>(
value: value,
//hint: Text(widget.label ?? ''),
onChanged: (color) {
setState(() => value = color);
//widget.onChanged(color);
},
items: colors.map((e) => DropdownMenuItem(
value: e,
child: Container(
// width: 60.0,
//height: 10.0,
width: 60.0,
// height: widget.height,
color: e,
),
),
)
.toList(),
),
),
),
],),
),
SizedBox(
height: height*0.08,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 55.0,
width: 200,
child: RaisedButton(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Theme.of(context).primaryColorDark,
textColor: Colors.white,
child: Text('Save',textScaleFactor: 1.5,),
onPressed: (){
setState(() {
_save();
});
},
),
),
),
],
),
floatingActionButton:_speedDial(),
));
}
void moveToLastScreen() {
Navigator.pop(context, true);
}
void _save() async {
moveToLastScreen();
note.cust_id=customer.cust_id;
print(customer.cust_id);
print(note.cust_id);
int result;
if (note.note_id != null) { // Case 1: Update operation
result = await dbService.updateNote(note);
} else { // Case 2: Insert Operation
result = await dbService.insertNote(note);
}
if (result != 0) { // Success
FormHelper.showAlertDialog(context,'Status', 'Note Saved Successfully');
} else { // Failure
FormHelper.showAlertDialog(context,'Status', 'Problem Saving Note');
}
}
}
db_service.dart
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/models/languages_model.dart';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/models/user_model.dart';
import 'package:vers2cts/utils/db_helper.dart';
class DBService {
Future<int> insertNote(NoteModel note) async {
await DB.init();
var result = await DB.insert(NoteModel.table, note);
return result;
}
Future<List<NoteModel>> getCustomerNotes(int customer) async {
await DB.init();
var res = await DB.rawQuery("note WHERE cust_id = '$customer'");
int count = res.length;
List<NoteModel> notelist = List<NoteModel>();
// For loop to create a 'Note List' from a 'Map List'
for (int i = 0; i < count; i++) {
notelist.add(NoteModel.fromMap(res[i]));
}
return notelist;
}
}
note_model.dart
import 'model.dart';
class NoteModel extends Model {
static String table = 'note';
bool isSelected=false;
int note_id;
int cust_id;
String note;
String actn_on;
int rmnd_ind;
double prty;
String colr;
String sts;
int id;
String cre_date;
String cre_by;
String mod_date;
String mod_by;
int txn_id;
int delete_ind;
NoteModel({
this.note_id,
this.cust_id,
this.note,
this.actn_on,
this.rmnd_ind,
this.prty,
this.colr,
this.sts,
this.id,
this.cre_date,
this.cre_by,
this.mod_date,
this.mod_by,
this.txn_id,
this.delete_ind
});
static NoteModel fromMap(Map<String, dynamic> map) {
return NoteModel(
note_id: map["note_id"],
cust_id: map['cust_id'],
note: map['note'].toString(),
actn_on: map['actn_on'].toString(),
rmnd_ind: map['rmnd_ind'],
prty: map['prty'],
colr: map['colr'].toString(),
sts: map['sts'].toString(),
id: map['id'],
cre_date: map['cre_date'].toString(),
cre_by: map['cre_by'].toString(),
mod_date: map['mod_date'].toString(),
mod_by: map['mod_by'].toString(),
txn_id: map['txn_id'],
delete_ind: map['delete_ind'],
);
}
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
'note_id': note_id,
'cust_id': cust_id,
'note':note,
'actn_on': actn_on,
'rmnd_ind': rmnd_ind,
'prty': prty,
'colr': colr,
'sts':sts,
'id': id,
'cre_date': cre_date,
'cre_by': cre_by,
'mod_date':mod_date,
'mod_by':mod_by,
'txn_id':txn_id,
'delete_ind': delete_ind
};
if (note_id != null) {
map['note_id'] = note_id;
}
return map;
}
}
db_helper.dart
import 'dart:async';
import 'package:vers2cts/models/model.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';
abstract class DB {
static Database _db;
static int get _version => 1;
static Future<Database> init() async {
if (_db != null) {
return _db;
}
try {
var databasesPath = await getDatabasesPath();
String _path = p.join(databasesPath, 'CTS.db');
_db = await openDatabase(_path, version: _version, onCreate: onCreate);
print('db location:'+_path);
} catch (ex) {
print(ex);
}
}
static void onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE note (note_id INTEGER PRIMARY KEY,cust_id INTEGER, '
'note TEXT, '
'actn_on TEXT, rmnd_ind INTEGER, prty REAL, colr TEXT,'
'sts TEXT,'
'id INTEGER, cre_date TEXT,cre_by TEXT, mod_date TEXT,mod_by TEXT, txn_id INTEGER, delete_ind INTEGER)');
}
static Future<List<Map<String, dynamic>>> query(String table) async =>
_db.query(table);
static Future<int> insert(String table, Model model) async =>
await _db.insert(table, model.toMap());
static Future<Batch> batch() async => _db.batch();
static Future<List<Map<String, dynamic>>> rawQuery(String table) async =>
_db.query(table);
}
You need to store what all values are selected from user and then play with it.
For example -
var selectedIndexes = [];
ListView getNotecheckList() {
return ListView.builder(
itemCount: count,
itemBuilder: (_, int index) {
return Card(
color: Colors.white,
elevation: 2.0,
child: CheckboxListTile(
title: Text(this.noteList[position].note),
subtitle: Text(this.noteList[position].actn_on),
value: selectedIndexes.contains(index),
onChanged: (_) {
if (selectedIndexes.contains(index)) {
selectedIndexes.remove(index); // unselect
} else {
selectedIndexes.add(index); // select
}
},
controlAffinity: ListTileControlAffinity.leading,
),
);
},
);
}
store only index or whole array and play around
Output :-
Code :-
import 'package:flutter/material.dart';
class CheckBoxExample extends StatefulWidget {
const CheckBoxExample({Key? key}) : super(key: key);
#override
State<CheckBoxExample> createState() => _CheckBoxExampleState();
}
class _CheckBoxExampleState extends State<CheckBoxExample> {
List multipleSelected = [];
List checkListItems = [
{
"id": 0,
"value": false,
"title": "Sunday",
},
{
"id": 1,
"value": false,
"title": "Monday",
},
{
"id": 2,
"value": false,
"title": "Tuesday",
},
{
"id": 3,
"value": false,
"title": "Wednesday",
},
{
"id": 4,
"value": false,
"title": "Thursday",
},
{
"id": 5,
"value": false,
"title": "Friday",
},
{
"id": 6,
"value": false,
"title": "Saturday",
},
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
child: Column(
children: [
Column(
children: List.generate(
checkListItems.length,
(index) => CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
dense: true,
title: Text(
checkListItems[index]["title"],
style: const TextStyle(
fontSize: 16.0,
color: Colors.black,
),
),
value: checkListItems[index]["value"],
onChanged: (value) {
setState(() {
checkListItems[index]["value"] = value;
if (multipleSelected.contains(checkListItems[index])) {
multipleSelected.remove(checkListItems[index]);
} else {
multipleSelected.add(checkListItems[index]);
}
});
},
),
),
),
const SizedBox(height: 64.0),
Text(
multipleSelected.isEmpty ? "" : multipleSelected.toString(),
style: const TextStyle(
fontSize: 22.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
],
),
),
);
}
}
I have created a reusable field that is called to display different fields in a form in different screen in my app i have also passed a controller however when dispose the controller it shows this error and if i go back to the same form screen it crashes.
class EntryField extends StatefulWidget {
#override
_EntryFieldState createState() => _EntryFieldState();
final String title;
final TextEditingController controller;
final TextInputType inputType;
final FilteringTextInputFormatter filter;
final hintText;
EntryField({#required this.title,this.hintText,#required this.controller,#required this.inputType,#required this.filter});
}
class _EntryFieldState extends State<EntryField> {
#override
void dispose() {
widget.controller.dispose();
print("anything");
super.dispose();
}
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
this.widget.title,
style: GoogleFonts.quicksand(
fontSize: 18,
)
),
SizedBox(
height: 10,
),
TextFormField(
controller: this.widget.controller,
keyboardType: this.widget.inputType,
inputFormatters: <TextInputFormatter>[
this.widget.filter,
],
validator: (value){
if(value.isEmpty){
return "${this.widget.title} is a Required Field";
}
return null;
},
decoration: InputDecoration(
hintText: this.widget.hintText,
border: InputBorder.none,
fillColor: Color(0xfff3f3f4),
filled: true,
errorBorder: new OutlineInputBorder(
borderSide: new BorderSide(color: Colors.red),
),
errorStyle: TextStyle(
fontSize: 15,
),
),
),
],
),
);
}
}
and in this class i am passing it field values
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final _serviceTitleController = TextEditingController();
final _serviceCategoryController = TextEditingController();
final _servicePriceController = TextEditingController();
ToastErrorMessage _error = ToastErrorMessage();
ToastValidMessage _valid = ToastValidMessage();
class AddServices extends StatefulWidget {
#override
_AddServicesState createState() => _AddServicesState();
}
class _AddServicesState extends State<AddServices> {
int currentIndex;
String _cityName;
final WorkshopServiceQueries _add = WorkshopServiceQueries();
final _firebaseUser = FirebaseAuth.instance.currentUser;
#override
void initState() {
cityName();
super.initState();
currentIndex = 0;
}
#override
void dispose() {
print("hello");
super.dispose();
}
void clearControllerText(){
_serviceTitleController.clear();
_serviceCategoryController.clear();
_servicePriceController.clear();
}
Future cityName() async{
_cityName = await _add.getWorkshopCityName();
}
changePage(int index) {
setState(() {
currentIndex = index;
});
}
validateFields() async{
final ValidateWorkshopServices service = ValidateWorkshopServices();
final int _price = int.tryParse(_servicePriceController.text.trim());
if(!service.validateServiceCategory(_serviceCategoryController.text.trim()) && !service.validateServiceTitle(_serviceTitleController.text.trim()) && !service.validateServicePrice(_price)){
_error.errorToastMessage(errorMessage: "Enter Valid Data in Each Field");
}
else if(!service.validateServiceCategory(_serviceCategoryController.text.trim())){
_error.errorToastMessage(errorMessage: "Service Category Must Only contain Alphabets");
}
else if(!service.validateServiceTitle(_serviceTitleController.text.trim())){
_error.errorToastMessage(errorMessage: "Service Title Must Only contain Alphabets");
}
else if(!service.validateServicePrice(_price)){
_error.errorToastMessage(errorMessage: "Service Price must be less than or equal to 2000");
}
else{
await addService(_price);
}
}
Future<void> addService(int price) async{
try {
Services data = Services(title: _serviceTitleController.text.trim(), category: _serviceCategoryController.text.trim(), price: price, workshopCity: _cityName, workshopId: _firebaseUser.uid);
await _add.addWorkshopService(data);
if(WorkshopServiceQueries.resultMessage == WorkshopServiceQueries.completionMessage){
_valid.validToastMessage(validMessage: WorkshopServiceQueries.resultMessage);
clearControllerText();
Future.delayed(
new Duration(seconds: 2),
(){
Navigator.pop(context);
},
);
}
else{
_error.errorToastMessage(errorMessage: WorkshopServiceQueries.resultMessage);
}
}catch(e){
_error.errorToastMessage(errorMessage: e.toString());
}
}
#override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
int _checkboxValue;
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(
'BIKERSWORLD',
style: GoogleFonts.quicksand(
color: Colors.white,
fontSize: 18,
),
),
backgroundColor: Color(0XFF012A4A),
leading: IconButton(icon:Icon(Icons.arrow_back, color: Colors.orange,),
onPressed:() => Navigator.pop(context),
)
),
body: Container(
height: height,
child: Stack(
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: 20),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: 30,),
_title(),
SizedBox(height: 40),
_addServicesWidget(),
SizedBox(height: 20),
FlatButton(
child: Container(
padding: EdgeInsets.symmetric(vertical: 15),
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.grey.shade200,
offset: Offset(2, 4),
blurRadius: 5,
spreadRadius: 2)
],
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [Color(0xfffbb448), Color(0xfff7892b)])),
child: Text(
'Register Now',
style: GoogleFonts.krub(
fontSize: 18,
color: Colors.white,
),
),
),
onPressed: (){
if(!_formKey.currentState.validate()){
return;
}
else{
validateFields();
}
},
),
SizedBox(height: 20),
],
),
),
),
],
),
),
),
);
}
}
Widget _addServicesWidget() {
return Form(
key: _formKey,
autovalidateMode: AutovalidateMode.disabled,
child: Column(
children: <Widget>[
EntryField(title: "Category",hintText: 'Mechanical',controller: _serviceCategoryController,inputType: TextInputType.text,filter: FilteringTextInputFormatter.allow(RegExp("[a-zA-Z ]"))),
SizedBox(height:15,),
EntryField(title: "Title",hintText: 'wheel barring',controller: _serviceTitleController,inputType: TextInputType.text,filter: FilteringTextInputFormatter.allow(RegExp("[a-zA-Z ]"))),
SizedBox(height:15,),
EntryField(title: "Price",hintText: 'price < 2000',controller: _servicePriceController,inputType: TextInputType.number,filter:FilteringTextInputFormatter.digitsOnly),
],
),
);
}
You shouldn't dispose the controller from within your widget, since you are creating it outside the widget and passing a reference to it into the widget.
It looks like your controllers are created in the global scope - if so, and if they are intended to be used throughout the lifetime of the app, you shouldn't dispose them.
So either
don't dispose the controllers if they are globals
or create and dispose them from the same "owner" object
for future comers, in my case i was using dispose twice for the same controller:
//error
void dispose() {
myController.dispose();
myController.dispose();
super.dispose();
}
//ok
void dispose() {
myController.dispose();
super.dispose();
}
I want to add Search Bar in Flutter. And I have achieved the state where I can type content in the search bar but during writing the query the List is not updating.
I want to sort on basis of blogName and below is the code
class AllBlogs extends StatefulWidget {
AllBlogs({Key key}) : super(key: key);
final Color _tabBackgroudColor = const Color(0xFF1A237E);
#override
AllBlogsState createState() {
return new AllBlogsState();
}
}
class AllBlogsState extends State<AllBlogs> {
Widget appBarTitle = Text("Blog's List");
Icon actionIcon = Icon(Icons.search, color: Colors.white,);
final key = new GlobalKey<ScaffoldState>();
final TextEditingController _searchQuery = new TextEditingController();
bool _IsSearching;
String _searchText = "";
_SearchListState() {
_searchQuery.addListener(() {
if (_searchQuery.text.isEmpty) {
setState(() {
_IsSearching = false;
_searchText = "";
});
}
else {
setState(() {
_IsSearching = true;
_searchText = _searchQuery.text;
});
}
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
_IsSearching = false;
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: buildBar(context),
body: new Container(
color: Colors.transparent,
child: ListView.builder(
itemCount: allblogs.length,
// Facing Issue Here
itemBuilder: _IsSearching ? buildSearchList : blogslist
),
),
);
}
// Facing Issue Here
Widget buildSearchList(BuildContext context, int index){
if (_searchText.isEmpty){
return blogslist(context, index);
}
else {
List<String> _searchList = List();
for (int i = 0; i < allblogs.length; i++) {
String name = (allblogs[index].blogName);
if (name.toLowerCase().contains(_searchText.toLowerCase())) {
_searchList.add(name);
}
}
// Now what can i return to show the tile whoes blogName I searched for
);
}
}
Widget buildBar(BuildContext context) {
return AppBar(
centerTitle: true,
title: appBarTitle,
backgroundColor: widget._tabBackgroudColor,
actions: <Widget>[
IconButton(icon: actionIcon,
onPressed: () {
setState(() {
if (this.actionIcon.icon == Icons.search) {
// ignore: new_with_non_type
this.actionIcon = new Icon(Icons.close, color: Colors.white,);
this.appBarTitle = TextField(
controller: _searchQuery,
style: TextStyle(
color: Colors.white,
),
decoration: InputDecoration(
prefixIcon: new Icon(Icons.search, color: Colors.white),
hintText: "Search...",
hintStyle: TextStyle(color: Colors.white)
),
);
_handleSearchStart();
}
else {
_handleSearchEnd();
}
});
},),
],
);
}
void _handleSearchStart() {
setState(() {
_IsSearching = true;
});
}
void _handleSearchEnd() {
setState(() {
// ignore: new_with_non_type
this.actionIcon = new Icon(Icons.search, color: Colors.white,);
this.appBarTitle = new Text("Search Sample", style: TextStyle(
color: Colors.white,
),);
_IsSearching = false;
_searchQuery.clear();
});
}
}
Widget blogslist(BuildContext context, int index){
return Container(
padding: const EdgeInsets.only(top: 5.0),
child: Column(
children: <Widget>[
ListTile(
leading: Padding(
padding: const EdgeInsets.all(3.0),
child: new Image(image: AssetImage("assets/images/icons/stackexchange.png")),
),
title: Text(allblogs[index].blogName,
),
subtitle: Text(allblogs[index].blogName),
contentPadding: EdgeInsets.symmetric(horizontal: 3.0),
isThreeLine: true,
trailing: Padding(padding: const EdgeInsets.only(left: 5.0),
child: IconButton(icon: Icon(Icons.launch, color: Colors.blue, size: 20.0,),
onPressed: (){}),
),
),
Divider(),
],
),
);
}
All I want is to search the ListTile widget in the flutter based on the title
You can also see the image which I uploaded that shows I achieved the situation in which I can type something in the search bar. Now I just need to compare the input text with the ListTile's title, and show the matched tiles.
I have created a list in different class like----
class AllBlogs {
final String id;
final String blogName;
final String blogurl;
final String about;
const AllBlogs(
{#required this.id,
#required this.blogName,
#required this.blogurl,
#required this.about});
}
List<AllBlogs> allblogs = [
const AllBlogs(
id: '1',
blogName: 'KDnuggets',
blogurl: "https://www.kdnuggets.com/?ref=cybrhome",
about: "KDnuggets is one of the most popular data science blogs, with articles that cover Business Analytics, Statistics, and Machine Learning.",
),
and when I am trying to write below code then at place of allblogs.It's showing an error of 'a value of type List can't be assigned to a variable of type List class.
You have a List<Blog> somewhere called allblogs. Each time the search text changes form a new sublist as follows:
List<Blog> sublist = allblogs.where((b) => b.name.toLowerCase().contains(_searchText.toLowerCase())).toList();
(if search text is empty then simply assign allblogs to sublist)
Now use sublist everywhere you currently use allblogs in your builds.
So, on every change to the search criterion, you filter the full list down to the sub list that matches and (as long as you do that in setState) the Widget tree redraws showing just the filtered list.
Here's a complete working example based on your snippet above:
import 'package:flutter/material.dart';
main() {
runApp(new MaterialApp(
title: 'Blogs Test',
home: new AllBlogs(),
));
}
class Blog {
String blogName;
Blog(this.blogName);
}
List<Blog> allblogs = [
Blog('flutter'),
Blog('dart'),
Blog('java'),
Blog('python'),
];
class AllBlogs extends StatefulWidget {
AllBlogs({Key key}) : super(key: key);
final Color _tabBackgroundColor = const Color(0xFF1A237E);
#override
AllBlogsState createState() => AllBlogsState();
}
class AllBlogsState extends State<AllBlogs> {
Widget appBarTitle = Text("Blog's List");
Icon actionIcon = Icon(
Icons.search,
color: Colors.white,
);
final key = new GlobalKey<ScaffoldState>();
final TextEditingController _searchQuery = new TextEditingController();
List<Blog> _displayList = allblogs;
#override
void initState() {
super.initState();
_searchQuery.addListener(() {
if (_searchQuery.text.isEmpty) {
setState(() {
_displayList = allblogs;
});
} else {
setState(() {
String s = _searchQuery.text;
_displayList = allblogs
.where((b) => b.blogName.toLowerCase().contains(s.toLowerCase()))
.toList();
});
}
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: buildBar(context),
body: new Container(
color: Colors.transparent,
child: ListView.builder(
itemCount: _displayList.length,
itemBuilder: _blogBuilder,
),
),
);
}
Widget _blogBuilder(BuildContext context, int index) {
return Container(
padding: const EdgeInsets.only(top: 5.0),
child: Column(
children: <Widget>[
ListTile(
leading: Padding(
padding: const EdgeInsets.all(3.0),
child: new Image(
image: AssetImage("assets/images/icons/stackexchange.png")),
),
title: Text(_displayList[index].blogName),
subtitle: Text(_displayList[index].blogName),
contentPadding: EdgeInsets.symmetric(horizontal: 3.0),
isThreeLine: true,
trailing: Padding(
padding: const EdgeInsets.only(left: 5.0),
child: IconButton(
icon: Icon(
Icons.launch,
color: Colors.blue,
size: 20.0,
),
onPressed: () {}),
),
),
Divider(),
],
),
);
}
Widget buildBar(BuildContext context) {
return AppBar(
centerTitle: true,
title: appBarTitle,
backgroundColor: widget._tabBackgroundColor,
actions: <Widget>[
IconButton(
icon: actionIcon,
onPressed: () {
setState(() {
if (this.actionIcon.icon == Icons.search) {
this.actionIcon = new Icon(
Icons.close,
color: Colors.white,
);
this.appBarTitle = TextField(
controller: _searchQuery,
style: TextStyle(
color: Colors.white,
),
decoration: InputDecoration(
prefixIcon: new Icon(Icons.search, color: Colors.white),
hintText: "Search...",
hintStyle: TextStyle(color: Colors.white)),
);
} else {
this.actionIcon = new Icon(
Icons.search,
color: Colors.white,
);
this.appBarTitle = new Text(
"Search Sample",
style: TextStyle(
color: Colors.white,
),
);
_searchQuery.clear();
}
});
},
),
],
);
}
}