I wanted to show the result or content in Full Screen after clicking on Suggested List from the Search bar, not below the Search bar as shown in the provided Screenshot below...
Tried to follow up with the flutter boring show, but not able to understand how they achieve it 😅.
Thanks in Advance !!!
import 'package:flutter/material.dart';
import 'urls_index.dart';
import 'ContentPage.dart';
class DataSearch extends SearchDelegate<String> {
var names = new urlsindexs();
#override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = "";
},
),
];
}
#override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
close(context, null);
});
}
#override
Widget buildResults(BuildContext context) {
return ContentPage();
}
#override
Widget buildSuggestions(BuildContext context) {
// TODO: implement buildSuggestions
var abc = query.isEmpty
? names.websitename
: names.websitename
.where((p) => p.toUpperCase().startsWith(query.toUpperCase()))
.toList();
return ListView.builder(
itemBuilder: (context, index) => ListTile(
onTap: () {
showResults(context);
},
title: RichText(
text: TextSpan(
text: abc[index].substring(0, query.length),
style: TextStyle(
color: Colors.black54, fontWeight: FontWeight.bold),
children: [
TextSpan(
text: abc[index].substring(query.length),
style: TextStyle(color: Colors.grey))
]),
),
),
itemCount: abc.length,
);
}
}
Getting This : https://ibb.co/vYW4G3x
Wanted to achieve This : https://ibb.co/pzBpNPK (without searchbar)
SOLVED !
What i changed...
import 'package:flutter/material.dart';
import 'urls_index.dart';
class DataSearch extends SearchDelegate<String> {
var names = new urlsindexs();
#override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = "";
},
),
];
}
#override
Widget buildLeading(BuildContext context) {
// TODO: implement buildLeading
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
close(context, null);
});
}
#override
Widget buildResults(BuildContext context) {
// TODO: implement buildResults
var abc = query.isEmpty
? names.websitename
: names.websitename
.where((p) => p.toUpperCase().startsWith(query.toUpperCase()))
.toList();
return ListView.builder(
itemBuilder: (context, index) => ListTile(
onTap: () {
showResults(context);
},
title: RichText(
text: TextSpan(
text: abc[index].substring(0, query.length),
style: TextStyle(
color: Colors.black54, fontWeight: FontWeight.bold),
children: [
TextSpan(
text: abc[index].substring(query.length),
style: TextStyle(color: Colors.grey))
]),
),
),
itemCount: abc.length,
);
}
#override
Widget buildSuggestions(BuildContext context) {
// TODO: implement buildSuggestions
var abc = query.isEmpty
? names.websitename
: names.websitename
.where((p) => p.toUpperCase().startsWith(query.toUpperCase()))
.toList();
return ListView.builder(
itemBuilder: (context, index) => ListTile(
onTap: () {
// showResults(context);
Navigator.of(context).pushNamed("/Store1");
},
title: RichText(
text: TextSpan(
text: abc[index].substring(0, query.length),
style: TextStyle(
color: Colors.black54, fontWeight: FontWeight.bold),
children: [
TextSpan(
text: abc[index].substring(query.length),
style: TextStyle(color: Colors.grey))
]),
),
),
itemCount: abc.length,
);
}
}
Related
Executed program picture I need help. I want to make the button click circular instead of rectangular.
This is the flutter dart code that I've provided, I want to know what attribute I should change or insert for making my question possible.
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(MaterialApp(
title: 'Ask me anything',
home: Scaffold(
appBar: AppBar(
title: Text('Ask me anything'),
centerTitle: true,
backgroundColor: Colors.blue[700],
),
backgroundColor: Colors.blue[800],
body: MyApp(),
),
));
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int ballNumber = 1;
#override
Widget build(BuildContext context) {
return Center(
child: Expanded(
child: TextButton(
style: ButtonStyle(enableFeedback: true,shape: ),
onPressed: () => setState(() {
ballNumber = Random().nextInt(5) + 1;
}),
child: Image.asset(
'images/ball$ballNumber.png',
width: 400,
// height: 200,
),
),
));
}
}
You can either change button style, or just wrap the image with GestureDetector.
Round Button
ElevatedButton(
style: ElevatedButton.styleFrom(
shape: const CircleBorder(),
padding: const EdgeInsets.all(50),
),
onPressed: () {},
child: const FittedBox(
child: Text('Round Button'),
),
),
ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all<CircleBorder>(
const CircleBorder(),
),
padding: MaterialStateProperty.all<EdgeInsets>(
const EdgeInsets.all(50),
),
),
onPressed: () {},
child: const FittedBox(
child: Text('Round Button'),
),
),
GestureDetector
GestureDetector(
onTap: () {
setState(() {
ballNumber = Random().nextInt(5) + 1;
});
},
child: Image.asset('images/ball$ballNumber.png'),
),
I am implementing Curved_Navigation_Bar in my Flutter poject and I am not using any class(i.e. Stateful / Stateless). I want to change the state of the icons that are in my curved_navigation_bar, means I want that animation effect on my navigation bar. Because the respective pages of those icons are navigating but not those items. No matter on which icon I click, it is still showing that first icon only. The animation/interpolation of icons is not happening.
As I am not using any Stateful/Stateless class, so I am not using Scaffold. Inside Scaffold we can change the state of the current object using setState(() { }).
So how can I change the state of my navigation bar?
Here is my code below:
navigation_bar.dart
import 'package:flutter/material.dart';
import 'package:curved_navigation_bar/curved_navigation_bar.dart';
import 'package:thehelpdesk/components/home/history.dart';
import 'package:thehelpdesk/components/home/home.dart';
import 'package:thehelpdesk/components/home/menu.dart';
import 'package:thehelpdesk/components/home/notification.dart';
import 'package:thehelpdesk/components/home/person.dart';
int currentIndex = 0 ;
Widget navBarSection(Color color, Color btnColor, BuildContext context) {
return CurvedNavigationBar(
index: 0,
items:
[
Icon(Icons.home, color: Colors.white),
Icon(Icons.notifications, color: Colors.white),
Icon(Icons.menu, color: Colors.white),
Icon(Icons.history, color: Colors.white),
Icon(Icons.person, color: Colors.white),
],
color: color,
buttonBackgroundColor: btnColor,
animationCurve: Curves.easeInCubic,
animationDuration: Duration(milliseconds: 600),
onTap: (index) {
if(currentIndex == 0){
Navigator.of(context).push(MaterialPageRoute(builder: (context) => HomePage()));
currentIndex = index ;
}
if(currentIndex == 1){
Navigator.of(context).push(MaterialPageRoute(builder: (context) => NotificationPage()));
currentIndex = index ;
}
if(currentIndex == 2){
Navigator.of(context).push(MaterialPageRoute(builder: (context) => MenuPage()));
currentIndex = index ;
}
if(currentIndex == 3){
Navigator.of(context).push(MaterialPageRoute(builder: (context) => HistoryPage()));
currentIndex = index ;
}
if(currentIndex == 4){
Navigator.of(context).push(MaterialPageRoute(builder: (context) => PersonPage()));
currentIndex = index ;
}
}
);
One of the pages I want to navigate on tapping a icon:
home.dart
import 'package:flutter/material.dart';
import 'package:thehelpdesk/widgets/appbar.dart';
import 'package:thehelpdesk/widgets/navigation_bar.dart';
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: aapBarSection('Home', Colors.blueAccent[700], context),
bottomNavigationBar: navBarSection(
Colors.blueAccent[700],
Colors.blueAccent[700],
context
),
);
}
}
Another page on tapping the 2nd icon:
notification.dart
import 'package:flutter/material.dart';
import 'package:thehelpdesk/widgets/appbar.dart';
import 'package:thehelpdesk/widgets/navigation_bar.dart';
class NotificationPage extends StatefulWidget {
#override
_NotificationPageState createState() => _NotificationPageState();
}
class _NotificationPageState extends State<NotificationPage> {
final message = [
'Hi Xyz,your invoice for It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.',
'Hi Xyz, Agility Rehab Care wishing you a very happy birthday! for It has survived not only five centuries, but also the leap remaining essentially unchanged.',
'Hi Xyz, From our Agility Rehab Care you are being reminded that you have an appointment with us on this Friday.',
'Hi Xyz, This is a reminder for you from Agility Rehab Care It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.',
];
final images = [
'assets/images/Invoice.png',
'assets/images/cake.png',
'assets/images/calender.png',
'assets/images/Reminder.png'
];
String date = '22/02/2021';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: aapBarSection('Notification',Colors.blueAccent[700],context),
bottomNavigationBar: navBarSection(
Colors.blueAccent[700],
Colors.blueAccent[700],
context
),
body: ListView.builder(
itemCount: message.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.fromLTRB(10, 10, 10, 10),
child: SizedBox(
height: 200,
child: Card(
elevation: 5.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
child: Column(
children: [
Flexible(
flex: 7,
child: Container(
child: Row(
children: [
Expanded(
flex: 2,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
images[index]))),
),
),
Expanded(
flex: 8,
child: Container(
child: Text(message[index]),
),
),
],
),
),
),
Flexible(
flex: 3,
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 10, 10, 10),
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [Text(date)],
),
),
),
),
],
),
),
)),
),
);
})
);
}
}
The short answer is that just add currentIndex as one of the parameter inside your navBarSection.
navigation_bar.dart
Widget navBarSection(
int currentIndex,
Color color,
Color btnColor,
BuildContext context,
) {
return CurvedNavigationBar(
index: currentIndex,
items: [
Icon(Icons.home, color: Colors.white),
Icon(Icons.notifications, color: Colors.white),
Icon(Icons.menu, color: Colors.white),
Icon(Icons.history, color: Colors.white),
Icon(Icons.person, color: Colors.white),
],
color: color,
buttonBackgroundColor: btnColor,
animationCurve: Curves.easeInCubic,
animationDuration: Duration(milliseconds: 600),
onTap: (index) {
if (currentIndex == 0) {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => HomePage()));
currentIndex = index;
}
if (currentIndex == 1) {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => NotificationPage()));
currentIndex = index;
}
if (currentIndex == 2) {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => MenuPage()));
currentIndex = index;
}
if (currentIndex == 3) {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => HistoryPage()));
currentIndex = index;
}
if (currentIndex == 4) {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => PersonPage()));
currentIndex = index;
}
});
}
Inside home.dart, just pass the currentIndex of the page.
home.dart
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: aapBarSection('Home', Colors.blueAccent[700], context),
bottomNavigationBar: navBarSection(
0,
Colors.blueAccent[700],
Colors.blueAccent[700],
context,
),
);
}
}
This should solve your problem but as you can see, this is not the best way to implement the bottomnavigationbar and widget due to:
You will lose the animation that the package provided.
It does not comply with the bottom navigation behavior since it will navigate to a new page instead of replacing it.
To solve this, create a new stateful widget,as for this example, I called it main_page.dart.
main_page.dart
class MainPage extends StatefulWidget {
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
int _currentIndex = 0;
List<Widget> _pages = [
HomePage(),
NotificationPage(),
MenuPage(),
HistoryPage(),
PersonPage(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: _pages.elementAt(_currentIndex),
bottomNavigationBar: CurvedNavigationBar(
backgroundColor: Colors.blueAccent,
items: [
Icon(Icons.home, color: Colors.white),
Icon(Icons.notifications, color: Colors.white),
Icon(Icons.menu, color: Colors.white),
Icon(Icons.history, color: Colors.white),
Icon(Icons.person, color: Colors.white),
],
color: Colors.blueAccent[700],
buttonBackgroundColor: Colors.blueAccent[700],
animationCurve: Curves.easeInCubic,
animationDuration: Duration(milliseconds: 600),
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
),
);
}
}
Called the the main_page.dart inside your main.dart.
main.dart
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MainPage(),
);
}
}
lastly, remove any bottomNavigationBar from home,history,menu,notification,and person page.
The result is
I'm trying to make a template for a filter that takes in one parameter (the tag name) and gets highlighted when tapped. But the problem with this is when one filter is tapped all of them change color because they all use the same boolean value. Sorry, I'm a beginner and I think I'm going about this the wrong way
class _HomeState extends State<Home> {
bool filterTap = true;
GestureDetector filterTemplate(String tag) {
return GestureDetector(
onTap: () {
setState(() {
filterTap = !filterTap;
});
},
child: Center(
child: Container(
margin: const EdgeInsets.only(right: 20.0),
padding: const EdgeInsets.symmetric(vertical: 5.0, horizontal: 10.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.all(Radius.circular(4.0)),
color: filterTap ? Colors.grey : Colors.transparent,
),
child: Text(
tag,
style: TextStyle(
color: filterTap ? Colors.grey[900] : Colors.grey,
letterSpacing: 2.0,
),
),
),
),
);
}
first of all define a StructFilter class with its properties, For example here is an option:
class StructFilter {
StructFilter(this.tag,this.filterTap);
String tag;
bool filterTap;
}
Then collect all of your filter information into a list of StructFilter(i.e List<StructFilter> filterList).
For example you can try:
Listview(
children: filterList.map((item){
return filterTemplate(item);
}).toList();
)
GestureDetector filterTemplate(StructFilter structFilter) {
return GestureDetector(
onTap: () {
setState(() {
structFilter.filterTap = !structFilter.filterTap;
});
},
),
);
}
Use List or Map or List<YourClass> to maintain status of each button.
And try ChoiceChip,
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: Home()));
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
Map<String, bool> tagsList = {
"Tag1": false,
"Tag2": false,
"Tag3": false,
"Tag4": false,
};
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Row(
children: tagsList.entries.map((entry) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ChoiceChip(
label: Text(entry.key),
selected: entry.value,
onSelected: (value) {
setState(() {
tagsList[entry.key] = value;
});
},
),
);
}).toList(),
),
),
);
}
}
I'm trying to add a search feature to this flutter app since the json file it pulls data from has 7000 results.
Mainly I'm trying to do search for "ctry" and "peopnameincountry". This was ripped from https://www.youtube.com/watch?v=EwHMSxSWIvQ
As is .. it works fine in fetching the json list and the tap to show detail page works as well.
I just need to implement the search on the main page so I don't have to scroll through the thousands of results.
Appreciate any help .. thank you all.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(new UnReached());
class UnReached extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Unreached'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<List<User>> _getUsers() async {
var data = await http.get("https://cmfiflutterapp.s3-ap-southeast-2.amazonaws.com/UnreachedPeoplesGroup.json");
var jsonData = json.decode(data.body);
List<User> users = [];
for(var u in jsonData){
User user = User(u["ctry"], u["peopnameincountry"], u["population"], u["primarylanguagename"], u["biblestatus"], u["primaryreligion"], u["continent"]);
users.add(user);
}
print(users.length);
return users;
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text(widget.title),
),
body: Container(
child: FutureBuilder(
future: _getUsers(),
builder: (BuildContext context, AsyncSnapshot snapshot){
print(snapshot.data);
if(snapshot.data == null){
return Container(
child: Center(
child: Text("Loading...")
)
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: Icon(Icons.arrow_forward_ios),
// leading: CircleAvatar(
// backgroundImage: NetworkImage(
// snapshot.data[index].picture
// ),
// ),
title: Text(snapshot.data[index].peopnameincountry),
subtitle: Text(snapshot.data[index].ctry),
onTap: (){
Navigator.push(context,
new MaterialPageRoute(builder: (context) => DetailPage(snapshot.data[index]))
);
},
);
},
);
}
},
),
),
);
}
}
Try adding these function in your code:
import 'package:flutter/material.dart';
import 'dart:core';
class HomeScreen1 extends StatefulWidget {
#override
HomeScreenState createState() => HomeScreenState();
}
class HomeScreenState extends State<HomeScreen1> {
var searchController = new TextEditingController();
String search;
List<String> _filterList;
String _query = "";
bool _firstSearch = true;
#override
void initState() {
super.initState();
}
HomeScreenState() {
searchController.addListener(() {
if (searchController.text.isEmpty) {
setState(() {
_firstSearch = true;
_query = "";
});
} else {
setState(() {
_firstSearch = false;
_query = searchController.text;
});
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: new Container(
margin: EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0),
child: new Column(
children: <Widget>[
_createSearchView(),
new Expanded(
child: _firstSearch ? _createListView() : _performSearch(),
),
],
),
),
);
}
Widget _createSearchView() {
return new Container(
decoration: BoxDecoration(border: Border.all(width: 1.0)),
child: new TextField(
controller: searchController,
decoration: InputDecoration(
icon: Icon(Icons.search),
hintText: "Search",
hintStyle: new TextStyle(color: Colors.grey[300]),
),
//textAlign: TextAlign.center,
),
);
}
Widget _createListView() {
return FutureBuilder(
future: _getUsers(),
builder: (BuildContext context, AsyncSnapshot snapshot){
print(snapshot.data);
if(snapshot.data == null){
return Container(
child: Center(
child: Text("Loading...")
)
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: Icon(Icons.arrow_forward_ios),
// leading: CircleAvatar(
// backgroundImage: NetworkImage(
// snapshot.data[index].picture
// ),
// ),
title: Text(snapshot.data[index].peopnameincountry),
subtitle: Text(snapshot.data[index].ctry),
onTap: (){
Navigator.push(context,
new MaterialPageRoute(builder: (context) => DetailPage(snapshot.data[index]))
);
},
);
},
);
}
},
),
}
Widget _performSearch() {
return FutureBuilder<List>(builder: (context, snapshot) {
_filterList = new List<String>();
for (int i = 0; i < snapshot.data.length; i++) {
var item = snapshot.data[i];
if ((item.toString().toLowerCase()).contains(_query.toLowerCase())) {
_filterList.add(item.toString());
}
}
return _createFilteredListView();
});
}
Widget _createFilteredListView() {
return ListView.builder(
itemCount: _filterList.length,
itemBuilder: (BuildContext context, int index) {
return new Card(
color: Colors.white,
elevation: 5.0,
child: new Container(
margin: EdgeInsets.all(15.0),
child: new Text("${_filterList[index]}"),
),
);
});
}
}
The concept of a FutureBuilder widget is to be build as soon as it is received, but meanwhile, the snapshot contains no data at all. So when you're calling :
for (int i = 0; i < snapshot.data.length; i++) {
you're, at least at first, calling length on null since the data is not yet received.
The solution is to create a switch and call `snapshot.data when the status is completed:
switch (snapshot.connectionState) {
case ConnectionState.none:
return DefaultWidget(); // For instance a CircularProgress
case ConnectionState.active:
return DefaultWidget(); // For instance a CircularProgress
case ConnectionState.waiting:
return DefaultWidget(); // For instance a CircularProgress
case ConnectionState.done:
if (snapshot.hasError)
return ErrorWidget('Error: ${snapshot.error}'); //For example a Text Widget
// Your code here:
_filterList = new List<String>();
for (int i = 0; i < snapshot.data.length; i++) {
var item = snapshot.data[i];
if ((item.toString().toLowerCase()).contains(_query.toLowerCase())) {
_filterList.add(item.toString());
}
}
return _createFilteredListView();
}
return null; // unreachable
More on this here
My apologies guys...I ended up taking a slightly different approach which I thought was slightly faster in response than the FutureBuilder approach. Maybe it's just my internet. Not sure.
import 'package:flutter/material.dart';
import 'dart:core';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'package:progress_indicators/progress_indicators.dart';
class IslandWaves extends StatefulWidget {
#override
HomeScreenState createState() => HomeScreenState();
}
class HomeScreenState extends State<IslandWaves> {
List<User> _list = [];
List<User> _search = [];
var loading = false;
Future<Null> fetchData() async {
setState(() {
loading = true;
});
_list.clear();
final response = await http.get(
"https://cmfiflutterapp.s3-ap-southeast-2.amazonaws.com/UnreachedPeoplesGroup.json");
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
setState(() {
for (Map i in data) {
_list.add(User.formJson(i));
loading = false;
}
});
}
}
TextEditingController controller = new TextEditingController();
onSearch(String text) async {
_search.clear();
if (text.isEmpty) {
setState(() {});
return;
}
_list.forEach((f) {
if (f.ctry.contains(text) ||
f.peopnameincountry.toString().contains(text)) _search.add(f);
});
setState(() {});
}
#override
void initState() {
// TODO: implement initState
super.initState();
fetchData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(10.0),
color: Colors.blue,
child: Card(
child: ListTile(
leading: Icon(Icons.search),
title: TextField(
controller: controller,
onChanged: onSearch,
decoration: InputDecoration(
hintText: "Search", border: InputBorder.none),
),
trailing: IconButton(
onPressed: () {
controller.clear();
onSearch('');
},
icon: Icon(Icons.cancel),
),
),
),
),
loading
? Center(
heightFactor: 20.0,
child: FadingText('Loading...'),
)
: Expanded(
child: _search.length != 0 || controller.text.isNotEmpty
? ListView.builder(
itemCount: _search.length,
itemBuilder: (context, i) {
final b = _search[i];
return GestureDetector(
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
DetailPage(_search[i])));
debugPrint('TopNav');
},
child: Container(
padding: EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
b.ctry,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
SizedBox(
height: 4.0,
),
Text(b.peopnameincountry),
],
)),
);
},
)
: ListView.builder(
itemCount: _list.length,
itemBuilder: (context, i) {
final a = _list[i];
return GestureDetector(
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
DetailPage(_list[i])));
debugPrint('BottomNav');
},
child: Container(
padding: EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
a.ctry,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
SizedBox(
height: 4.0,
),
Text(a.peopnameincountry),
],
)
),
);
},
),
),
],
),
),
);
}
}
class DetailPage extends StatelessWidget{....etc.}
I am a newbie to flutter, I am having a problem with passing the data to my search delegate class. The problem is that I have two tabs and I want to search within the active tab. So I am trying to send a variable that tells which tab is it and which table to look for value.
Here is what my code looks like:
class HomePage extends StatefulWidget {
static final String routeName = 'home';
#override
State<StatefulWidget> createState() {
return new _HomePageState();
}
}
class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
var activeTab = "activity";
var _authToken, _id, _name, _emails, _userImage;
#override
void initState() {
super.initState();
tabController = TabController(vsync: this, length: 2)..addListener(() {
setState(() {
switch (tabController.index) {
case 0:
activeTab = "activity";
break;
case 1:
activeTab = "subparticipants";
break;
}
});
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
key: _scaffoldKey,
// appBar: new AppBar(
// title: Text('Dashboard'),
// ),
body: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
labelColor: Color(0xFFFFFFFF),
indicatorSize: TabBarIndicatorSize.tab,
tabs: [
//Tab(icon: Icon(Icons.directions_car)),
Tab(
text: "Activity Zone",
),
Tab(
text: "Sub Participant",
)
],
controller: tabController,
),
title: Text(
'Dashboard',
style: new TextStyle(
color: const Color(0xFFFFFFFF),
fontSize: 20.0,
fontWeight: FontWeight.w600,
letterSpacing: 0.3,
),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(context: context, delegate: DataSearch(activeTab));
},
)
],
),
body: TabBarView(
controller: tabController,
children: [
TabActivity(),
TabSubparticipant(),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
print(
'Current Index: $activeTab');
},
),
drawer: _buildDrawer(context),
),
),
);
}
}
class DataSearch extends SearchDelegate{
final String activeTab;
DataSearch(this.activeTab);
#override
List<Widget> buildActions(BuildContext context){
return [
IconButton(
icon: Icon(Icons.arrow_back),
onPressed: (){
query=activeTab;
},
)
];
}
#override
Widget buildLeading(BuildContext context) => IconButton(
icon: Icon(Icons.close),
onPressed: () => Navigator.of(context).pop(),
);
#override
Widget buildResults(BuildContext context) => Text('Result');
#override
Widget buildSuggestions(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Search by job id, asset name, client name $query',
style: new TextStyle(
color: Colors.black, fontWeight: FontWeight.bold, fontSize: 22.0),
),
);
}
}
When I try to get $activeTab and show it in query or somewhere else, It just gives out the error:
flutter: The following assertion was thrown building _SearchPage<dynamic>(dirty, dependencies:
flutter: [_LocalizationsScope-[GlobalKey#a02e3], _InheritedTheme], state: _SearchPageState<dynamic>#eceaa):
flutter: 'package:flutter/src/widgets/basic.dart': Failed assertion: line 6173 pos 15: 'child != null': is
I am a bit confused how should I pass value to it. I have seen some of similar questions but they are no help. Like this or this question. None of these have any of these errors. Can you please let me know what am I doing wrong. Whats the issue? Please help.
Well, For someone who dumb as me and is having the same problem as I am, Here is how you can fix the issue,
So I was not passing the correct value to Search delegate and was not picking it up properly. Here is the fixed part of code
class DataSearch extends SearchDelegate {
DataSearch({
#required this.activeTab,
});
final activeTab;
#override
Widget buildResults(BuildContext context) {
if (activeTab == "subparticipants") {
...... .
....
..