Using tabs to navigate screens in flutter - flutter

The tabs page have three tabs- Nearby,Recent and Notice tabs.
Tabs.dart-
class Tabs extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
SizedBox(width: 24),
MyTab(text: 'Nearby', isSelected: false),
MyTab(text: 'Recent', isSelected: true),
MyTab(text: 'Notice', isSelected: false),
],
);
}
}
class MyTab extends StatelessWidget {
final String text;
final bool isSelected;
const MyTab({Key key, #required this.isSelected, #required this.text})
: super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
text,
style: TextStyle(
fontSize: isSelected ? 16 : 14,
color: isSelected ? Colors.black : Colors.grey,
fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
),
),
Container(
height: 6,
width: 20,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: isSelected ? Color(0xFFFF5A1D) : Colors.white,
),
)
],
),
);
}
}
In the home-page.dart file the tabs defined in tabs.dart file is called but are non-functional -
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Stack(
children: <Widget>[
SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(height: 8),
Header(),
SizedBox(height: 40),
Tabs(),
SizedBox(height: 8),
SlidingCardsView(),
],
),
),
],
),
);
}
}
As you can see that the SlidingCardsView() is called below the tabs, but I want to open the SlidingCardsView() on clicking the recent tab and further PageOne() to Nearby and PageTwo() to notice tabs. Can anyone help me with this?.Thanks in Advance.

Here is the code, change things according to your needs further,
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Tabs(refresh: () => setState(() {})),
value == 0 ? Center(child: Text("Nearby Page", style: TextStyle(fontSize: 56))) : Container(),
value == 1 ? Center(child: Text("Recent Page", style: TextStyle(fontSize: 56))) : Container(),
value == 2 ? Center(child: Text("Notice Page", style: TextStyle(fontSize: 56))) : Container(),
],
),
),
);
}
}
class Tabs extends StatefulWidget {
final Function refresh;
Tabs({this.refresh});
#override
_TabsState createState() => _TabsState();
}
int value = 1;
class _TabsState extends State<Tabs> {
#override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
SizedBox(width: 24),
MyTab(text: 'Nearby', isSelected: value == 0, onTap: () => _updateValue(0)),
MyTab(text: 'Recent', isSelected: value == 1, onTap: () => _updateValue(1)),
MyTab(text: 'Notice', isSelected: value == 2, onTap: () => _updateValue(2)),
],
);
}
void _updateValue(int newValue) {
widget.refresh();
setState(() {
value = newValue;
});
}
}
class MyTab extends StatelessWidget {
final String text;
final bool isSelected;
final Function onTap;
const MyTab({Key key, #required this.isSelected, #required this.text, this.onTap}) : super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: onTap,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
text,
style: TextStyle(
fontSize: isSelected ? 16 : 14,
color: isSelected ? Colors.black : Colors.grey,
fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
),
),
Container(
height: 6,
width: 20,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: isSelected ? Color(0xFFFF5A1D) : Colors.white,
),
)
],
),
),
);
}
}

Related

AutomaticKeepAliveClientMixin not working with CupertinoSwitch

I have page where build ListView with CupertinoSwitch.
class NewsPageRegistr extends StatefulWidget {
NewsPageRegistr({Key key, this.model}) : super(key: key);
RegistrationModel model;
#override
_NewsPageRegistrState createState() => _NewsPageRegistrState();
}
class _NewsPageRegistrState extends State<NewsPageRegistr>
with AutomaticKeepAliveClientMixin<NewsPageRegistr> {
#override
bool get wantKeepAlive => true;
var responseV;
List<DigitalNews> digitalNews = [];
#override
void dispose() {
super.dispose();
}
#override
void initState() {
fitchData();
super.initState();
}
fitchData() async {
responseV = await apiRegistrationDataList(DropMenuMode.news);
for (var values in responseV) {
digitalNews.add(DigitalNews.fromJson(values));
}
}
#override
Widget build(BuildContext context) {
super.build(context);
return SingleChildScrollView(
child: SafeArea(
minimum: const EdgeInsets.fromLTRB(25, 0, 25, 0),
child: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
SizedBox(
width: 400,
height: 85,
child: Text(
"Ich möchte folgende Newsletter abonnieren",
textAlign: TextAlign.left,
style: GeneralStyles.titleStyle,
),
),
ListView.builder(
//padding: const EdgeInsets.symmetric(vertical: 8),
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: digitalNews.length,
itemBuilder: (context, index) {
return CheckWidget(
title: digitalNews[index].displayName,
subtitle: digitalNews[index].displayDescription,
registrationName: digitalNews[index].name,
index: index,
model: widget.model,
);
}),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
OutlinedButton(
style: OutlinedButton.styleFrom(
backgroundColor: GeneralStyles.petrolColor,
),
onPressed: () {
setState(() {});
widget.model.setCurrentPage(2);
},
child: const Text(
"Weiter",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w300,
fontFamily: 'FiraSans'),
)),
],
),
),
],
),
),
],
),
),
);
}
}
I use AutomaticKeepAliveClientMixin but it not working when i jump to next page (on PageView).
I add AutomaticKeepAliveClientMixin on main widget when call PageView, add to CheckWidget and to NewsPageRegistr widget but it not working. when i jump to other page on PageView List NewsPageRegistr state is dispose.
Code of widget:
class CheckWidget extends StatefulWidget {
RegistrationModel model;
bool checker = false;
final Function(String) onChanged;
final String title;
final String subtitle;
final String registrationName;
final int index;
CheckWidget({Key key, this.onChanged, this.title, this.subtitle, this.registrationName, this.index,this.model}) : super(key: key);
#override
State<CheckWidget> createState() => _CheckWidgetState();
}
class _CheckWidgetState extends State<CheckWidget> {
#override
Widget build(BuildContext context) {
return Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Transform.scale(
alignment: Alignment.centerLeft,
scale: 0.8,
child: CupertinoSwitch(
value: widget.checker,
activeColor: GeneralStyles.petrolColor,
onChanged: (bool value) {
setState(() {
widget.checker = value;
if(value == true) {
widget.model.newsPapers[widget.index] = widget.registrationName;
}else {
widget.model.newsPapers[widget.index] = '';
}
});
},
),
),
Expanded(
child: GestureDetector(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(widget.title.replaceFirst("Newsletter", "").trim(), style:TextStyle(
color: GeneralStyles.blackColor,
fontSize: 15,
fontFamily: 'FiraSans',
fontWeight: FontWeight.w400,
)),
Text(widget.subtitle, style:TextStyle(
color: GeneralStyles.blackColor,
fontSize: 13,
fontFamily: 'FiraSans',
fontWeight: FontWeight.w300,
)),
],
),
onTap: (){
setState(() {
if(widget.checker == false) {
widget.checker = true;
widget.model.newsPapers[widget.index] = widget.registrationName;
}else {
widget.checker = false;
widget.model.newsPapers[widget.index] = '';
}
});
},
),
),
]
),
);
}
}

flutter How to change text colour dynamically on tap?

I want to make a program where 2 options will be written on text and I want to make my program whenever the user choose one of those option the other option will be greyed out.
I've tried using text button, but it's still a bit wacky for my taste.
Try this:
class _MyHomePageState extends State<MyHomePage> {
int _selectIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Row(
children: [
InkWell(
onTap: () {
setState(() {
_selectIndex = 0;
});
},
child: Text(
'Celcius',
style: TextStyle(
color: _selectIndex == 0 ? Colors.black : Colors.grey,
),
),
),
const Text(' | '),
InkWell(
onTap: () {
setState(() {
_selectIndex = 1;
});
},
child: Text(
'Fashrenheit',
style: TextStyle(
color: _selectIndex == 1 ? Colors.black : Colors.grey,
),
),
),
],
),
),
);
}
}
You can use stateful widget to change states when button is pressed.
class HomePage extends StatefulWidget {
const HomePage({super.key});
#override
State<HomePage> createState() => _HomePageState();
}
enum Temperature { celcius, fahrenheit }
class _HomePageState extends State<HomePage> {
late Temperature _currentScale;
late num _currentTemp;
#override
void initState() {
super.initState();
_currentScale = Temperature.celcius;
_currentTemp = 24; //multiply by 1.8 add 32 C->F
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_currentScale == Temperature.celcius
? '$_currentTemp°C'
: '${_currentTemp * 1.8 + 32}°F',
style: Theme.of(context).textTheme.headline2,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
child: Text(
'Celcius',
style: TextStyle(
color: _currentScale == Temperature.celcius
? Colors.red
: Colors.grey),
),
onPressed: () =>
setState(() => _currentScale = Temperature.celcius)),
const SizedBox(
width: 10,
),
TextButton(
child: Text('Fahrenheit',
style: TextStyle(
color: _currentScale == Temperature.fahrenheit
? Colors.red
: Colors.grey)),
onPressed: () => setState(
() => _currentScale = Temperature.fahrenheit))
],
)
],
),
),
),
);
}
}
You can try ToggleButton instead of TextButton
ToggleButton
You can try this one. I hope this is useful to you !
class MyHomePage extends StatelessWidget {
final RxInt _selectIndex = 0.obs;
MyHomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Obx(
() => Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"25",
style: TextStyle(
fontSize: 30,
color: _selectIndex.value == 0 ? Colors.grey : Colors.black,
),
),
const SizedBox(
height: 10,
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
InkWell(
onTap: () {
_selectIndex.value = 0;
},
child: Text(
'Celcius',
style: TextStyle(
color: _selectIndex.value == 0 ? Colors.black : Colors.grey,
),
),
),
const Text(' | '),
InkWell(
onTap: () {
_selectIndex.value = 1;
},
child: Text(
'Fashrenheit',
style: TextStyle(
color: _selectIndex.value == 1 ? Colors.black : Colors.grey,
),
),
),
],
),
],
),
),
),
);
}
}

How do I pass a variable to a child widget?

I am passing a string value `final String userLogin; from another file via Route.
class AutfPasswordWidget extends StatefulWidget {
final String userLogin;
AutfPasswordWidget({Key? key, required this.userLogin}) : super(key: key);
#override
State<AutfPasswordWidget> createState() => _AutfPasswordWidgetState();
}
final iconColor = const Color(0xFF2787F5);
class _AutfPasswordWidgetState extends State<AutfPasswordWidget> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
leading: BackButton(
color: Colors.grey
),
elevation: 0,
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min, // Иконка по центру несмотря на кнопку назад
children: [
Icon(Icons.telegram_sharp, color: iconColor),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 2, vertical: 2)),
Text('ID', style: TextStyle(color: Colors.black, fontSize: 18)),
],
)),
body: Padding(
padding: const EdgeInsets.all(20),
child: ListView(
children: [
_MainInfoWidget(),
],
),
),
);
}
}
But I need to use the resulting value in another widget 'Use password for $userLogin' , located under it.
class _MainInfoWidget extends StatelessWidget {
const _MainInfoWidget({Key? key,}) : super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(
Icons.telegram_sharp,
color: iconColor,
size: 64,
),
SizedBox(height: 20),
Text('Password',
style: AppAuthTitleStyle.LinkButton),
SizedBox(height: 20),
Text(
'Use password for $userLogin' ,
style: AppDescribeTittleStyle.LinkButton,
textAlign: TextAlign.center,
),
],
),
);
}
}
How do I pass the value to the desired widget ?
You can pass userLogin to _mainInfoWidget() by accesing the parent variable using widget.userLogin:
_MainInfoWidget(userLogin: widget.userLogin),
Complete example:
class AutfPasswordWidget extends StatefulWidget {
final String userLogin;
AutfPasswordWidget({Key? key, required this.userLogin}) : super(key: key);
#override
State<AutfPasswordWidget> createState() => _AutfPasswordWidgetState();
}
final iconColor = const Color(0xFF2787F5);
class _AutfPasswordWidgetState extends State<AutfPasswordWidget> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
leading: BackButton(color: Colors.grey),
elevation: 0,
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize:
MainAxisSize.min, // Иконка по центру несмотря на кнопку назад
children: [
Icon(Icons.telegram_sharp, color: iconColor),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 2, vertical: 2)),
Text('ID', style: TextStyle(color: Colors.black, fontSize: 18)),
],
)),
body: Padding(
padding: const EdgeInsets.all(20),
child: ListView(
children: [
_MainInfoWidget(userLogin: widget.userLogin),
],
),
),
);
}
}
class _MainInfoWidget extends StatelessWidget {
final String? userLogin;
const _MainInfoWidget({
this.userLogin,
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(
Icons.telegram_sharp,
color: iconColor,
size: 64,
),
SizedBox(height: 20),
Text(
'Password',
),
SizedBox(height: 20),
Text(
'Use password for $userLogin',
// style: AppDescribeTittleStyle.LinkButton,
textAlign: TextAlign.center,
),
],
),
);
}
}

Tried creating tabs in product detail page in flutter. But tabs is in stateful widget. When I inserted tab class name in home class, getting error

I need to insert tabs below elevated button. When I am using it as separate file, its working fine. Please suggest any ways to insert tabs in this code. I am in the learning stage of flutter.Here is the code link on codepen.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: Home());
}
}
class TabsPart extends StatefulWidget {
#override
_TabsPartState createState() => _TabsPartState();
}
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: const Text('Welcome to Flutter'),
),
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: [
Positioned(
child: Container(
alignment: Alignment.topCenter,
decoration: const BoxDecoration(
image: DecorationImage(
alignment: Alignment.bottomRight,
fit: BoxFit.cover,
image: AssetImage('assets/images/img1.png'))),
),
),
Positioned(
bottom: 0,
child: Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Colors.lightBlue,
borderRadius: BorderRadius.circular(14),
),
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Container(
margin: const EdgeInsets.only(bottom: 16),
width: 12 * 1.5,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(3),
),
),
),
const ProductNameAndPrice(),
const Spacing(),
const ProductDesc(),
const Spacing(),
const SizedBox(
height: 16,
),
ElevatedButton(
style: ElevatedButton.styleFrom(
onSurface: Colors.white),
onPressed: null,
child: Text('Add to Cart',
style: TextStyle(
color: Colors.white, fontSize: 16)),
),
const Spacing(),
],
),
),
))
],
),
),
),
),
);
}
}
class Spacing extends StatelessWidget {
const Spacing({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return const SizedBox(
height: 16,
);
}
}
class RectButton extends StatelessWidget {
final String label;
const RectButton({
Key? key,
required this.label,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 32,
width: 32,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(9),
border: Border.all(color: Colors.white)),
child: Center(
child: Text(
label,
style: TextStyle(color: Colors.white, fontSize: 20),
)),
);
}
}
class ProductNameAndPrice extends StatelessWidget {
const ProductNameAndPrice({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Product 1',
style: TextStyle(
color: Color.fromARGB(255, 250, 235, 235), fontSize: 30),
),
Text(
'\u{20B9}${150}',
style: TextStyle(color: Colors.white, fontSize: 20),
),
],
);
}
}
class ProductDesc extends StatelessWidget {
const ProductDesc({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'This is a good product with \nexcellent quality. purchase it as soon as possible! \nFew numbers only Left in stocks',
style: TextStyle(color: Colors.white, fontSize: 16, height: 1.6)),
],
);
}
}
class _TabsPartState extends State<TabsPart> {
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(
icon: Icon(Icons.android),
text: "Tab 1",
),
Tab(icon: Icon(Icons.phone_iphone), text: "Tab 2"),
],
),
title: Text('TutorialKart - TabBar & TabBarView'),
),
body: TabBarView(
children: [
Center(child: Text("Page 1")),
Center(child: Text("Page 2")),
],
),
),
);
}
}
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: Home());
}
}
class Home extends StatefulWidget {
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> with SingleTickerProviderStateMixin {
late TabController _tabController;
#override
void initState() {
_tabController = TabController(length: 2, vsync: this);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
const ProductNameAndPrice(),
const ProductDesc(),
const SizedBox(height: 16),
ElevatedButton(
style: ElevatedButton.styleFrom(onSurface: Colors.black),
onPressed: null,
child: Text('Add to Cart',
style: TextStyle(color: Colors.black, fontSize: 16)),
),
TabBar(
indicatorColor: Colors.grey,
controller: _tabController,
tabs: [
const Tab(
icon: Icon(
Icons.widgets,
color: Colors.black,
),
),
Tab(
icon: Icon(
Icons.widgets,
color: Colors.black,
),
),
],
),
Expanded(
child: TabBarView(
controller: _tabController,
children: const [
Text("POSTS"),
Text("REELS"),
],
),
),
]),
);
}
}
class RectButton extends StatelessWidget {
final String label;
const RectButton({
Key? key,
required this.label,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 32,
width: 32,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(9),
border: Border.all(color: Colors.white)),
child: Center(
child: Text(
label,
style: TextStyle(color: Colors.white, fontSize: 20),
)),
);
}
}
class ProductNameAndPrice extends StatelessWidget {
const ProductNameAndPrice({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Product 1',
style: TextStyle(color: Colors.black, fontSize: 30),
),
Text(
'\u{20B9}${150}',
style: TextStyle(color: Colors.black, fontSize: 20),
),
],
);
}
}
class ProductDesc extends StatelessWidget {
const ProductDesc({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'This is a good product with \nexcellent quality. purchase it as soon as possible! \nFew numbers only Left in stocks',
style: TextStyle(color: Colors.black, fontSize: 16, height: 1.6)),
],
);
}
}
try this

My search bar is not filtering any data from listview. Can anyone tell me what's wrong with my onItemChanged() function and how to solve the issue?

The app only shows listview but doesn't filter any data.
If I type anything in searchbar the list view remains same
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => new _HomeState();
}
class _HomeState extends State<Home> {
Future<List> getData() async {
final response =
await http.get(Uri.parse("http://192.168.0.166/api/conn2.php"));
return json.decode(response.body);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("MY APP"),
),
body: Center(child: ListSearch()));
}
}
class ListSearch extends StatefulWidget {
ListSearchState createState() => ListSearchState();
}
class ListSearchState extends State<ListSearch> {
TextEditingController _textController = TextEditingController();
List newList = [];
onItemChanged(String value) {
setState(() {
newList = MyStatelessWidget(
list: [],
)
.list
.where((string) => string.toLowerCase().contains(value.toLowerCase()))
.toList(); //copying api data into newList
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(12.0),
child: TextField(
controller: _textController,
decoration: InputDecoration(
hintText: "Search here....",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(4.0)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black)),
prefixIcon: Icon(Icons.search),
suffixIcon: IconButton(
onPressed: _textController.clear,
icon: Icon(Icons.clear),
),
),
onChanged: onItemChanged, //onItemChanged() called here
),
),
Expanded(
child: new FutureBuilder<List>(
future: _HomeState().getData(),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? new MyStatelessWidget(
list: snapshot.data ?? [],
)
: new Center(
child: CircularProgressIndicator(),
);
},
),
)
],
),
);
}
}
The database contains 'Articles','Features', 'Features2','Description' table
class _ArticleDescription extends StatelessWidget {
const _ArticleDescription({
Key? key,
required this.articles,
required this.features,
required this.features2,
//required this.description,
}) : super(key: key);
final String articles;
final String features;
final String features2;
// final String description;
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
articles,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
const Padding(padding: EdgeInsets.only(bottom: 2.0)),
Text(
features,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12.0,
color: Colors.black54,
),
),
],
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Text(
features2,
style: const TextStyle(
fontSize: 12.0,
color: Colors.black87,
),
),
/*Text(
description,
style: const TextStyle(
fontSize: 12.0,
color: Colors.black54,
),
),*/
],
),
),
],
);
}
}
Custom list view
class CustomListItemTwo extends StatelessWidget {
const CustomListItemTwo({
Key? key,
required this.thumbnail,
required this.articles,
required this.features,
required this.features2,
// required this.description,
}) : super(key: key);
final Widget thumbnail;
final String articles;
final String features;
final String features2;
//final String description;
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0),
child: SizedBox(
height: 80,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
AspectRatio(
aspectRatio: 0.8,
child: thumbnail,
),
Expanded(
child: Padding(
padding: const EdgeInsets.fromLTRB(20.0, 0.0, 2.0,0.0),
child: _ArticleDescription(
articles: articles,
features: features,
features2: features2,
// description: description,
),
),
)
],
),
),
);
}
}
class MyStatelessWidget extends StatelessWidget {
final List list;
//final List<String> list;
const MyStatelessWidget({ required this.list});
//const MyStatelessWidget({Key? key, required this.list}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: list == null ? 0 : list.length,
itemBuilder: (context, i) {
return Container(
padding: const EdgeInsets.all(10.0),
child: new GestureDetector(
onTap: ()=>Navigator.of(context).push(
new MaterialPageRoute(
builder: (BuildContext context)=> new Detail(list:list , index: i,)
)
),
child:Column(
children:<Widget> [
CustomListItemTwo(
thumbnail: Container(
decoration: const BoxDecoration(color: Colors.blue),
),
articles: (list[i]['Articles']),
features: (list[i]['Features']),
features2: (list[i]['Features2']),
//description: (list[i]['Description']),
),
],
),
),
);
}
);
}
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: list == null ? 0 : list.length,
....
To
#override
Widget build(BuildContext context) {
var activeList = searchlist ;
//create isSearchBar bool var. and change
//true if search is Active
//false if search is inActive
isSearchBar
? activeList = searchlist
: activeList = list;
return ListView.builder(
itemCount: activeList == null ? 0 : activeList.length,
....
articles: (activeList[i]['Articles']),
....