How to put Search container inside my Home.dart? - flutter

I have two dart file which are Home.dart and menuUser.dart. I've been following some tutorial in developing my apps. My problem now is, I don't know how to put my Search bar or container in my Home.dart because I already have appBar inside my menuUser.dart. I figure out if I put appBar inside my Home.dart, my apps will have double tab bar at the top.
Here is my menuUser.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:myapp/model/api.dart';
import 'package:myapp/view/home.dart';
import 'package:myapp/view/budget.dart';
import 'package:myapp/view/locationMap.dart';
import 'package:myapp/view/profile.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MenuUsers extends StatefulWidget {
final VoidCallback signOut;
MenuUsers(this.signOut);
#override
_MenuUsersState createState() => _MenuUsersState();
}
class _MenuUsersState extends State<MenuUsers> {
signOut(){
setState((){
widget.signOut();
});
}
String name = "";
TabController tabController;
getPref()async{
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
name = preferences.getString("name");
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
getPref();
}
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.pink,
actions: <Widget>[
IconButton(
onPressed: (){
signOut();
},
icon: Icon(Icons.lock_open),
)
],
),
body: TabBarView(
children: <Widget>[
Home(),
Budget(),
LocationMap(),
Profile(),
],
),
bottomNavigationBar: TabBar(
labelColor: Colors.pink,
unselectedLabelColor: Colors.grey,
indicator: UnderlineTabIndicator(
borderSide: BorderSide(
style: BorderStyle.none
)
),
tabs: <Widget>[
Tab(
icon: Icon(Icons.home),
text: "Home",
),
Tab(
icon: Icon(Icons.shopping_basket),
text: "Budget",
),
Tab(
icon: Icon(Icons.map),
text: "Location",
),
Tab(
icon: Icon(Icons.person),
text: "Profile",
)
],
),
),
);
}
}
and here is my Home.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:myapp/model/UserAttractionModel.dart';
import 'package:myapp/model/categoryProductModel.dart';
import 'package:myapp/network/network.dart';
import 'package:myapp/view/productDetail.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
var loading = false;
List<CategoryProductModel> listCategory = [];
getProductWithCategory() async{
setState(() {
loading = true;
});
listCategory.clear();
final response = await http.get(NetworkUrl.getProductCategory());
if(response.statusCode == 200){
final data = jsonDecode(response.body);
print(data);
setState(() {
for(Map i in data){
listCategory.add(CategoryProductModel.fromJson(i));
}
loading = false;
});
} else {
setState(() {
loading = false;
});
}
}
var filter = false;
List<UserAttractionModel> list =[];
getAttraction()async{
setState(() {
loading = true;
});
list.clear();
final response = await http.get(NetworkUrl.getAttraction());
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print(data);
setState(() {
for (Map i in data) {
list.add(UserAttractionModel.fromJson(i));
}
loading= false;
});
} else {
setState(() {
loading= false;
});
}
}
Future<void> onRefrash() async{
getAttraction();
getProductWithCategory();
setState(() {
filter = false;
});
}
int index = 0;
#override
void initState() {
// TODO: implement initState
super.initState();
getAttraction();
getProductWithCategory();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: loading ? Center(
child: CircularProgressIndicator(),
)
: RefreshIndicator(
onRefresh: onRefrash,
child: ListView(
children: <Widget>[
//Kategori attraction#produk
Container(
height: 50,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: listCategory.length,
itemBuilder: (context,i){
final a = listCategory[i];
return InkWell(
onTap: (){
setState(() {
filter = true;
index = i;
print(filter);
});
},
child: Container(
margin: EdgeInsets.only(left: 20, right: 1),
padding: EdgeInsets.all(15),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.deepOrangeAccent
),
child: Text(
a.categoryName,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
)
),
),
);
},
),
),
filter
? listCategory[index].attraction.length == 0
?
Container(
height: 100,
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Sorry Item on this category not available",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18),
),
],
),
)
: GridView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
padding: EdgeInsets.all(10),
itemCount: listCategory[index].attraction.length,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 15,
crossAxisSpacing: 8
),
itemBuilder: (context,i){
final a = listCategory[index].attraction[i];
return InkWell(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => ProductDetail(a)
)
);
},
child: Container(
padding: EdgeInsets.all(10),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded
(child: Image.network("http://192.168.42.48/myapp/upload/"+ a.image,
width: 100.0,
fit: BoxFit.cover,
height: 180,
),
),
SizedBox(
height: 4,
),
Text("${a.attractionName}", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.pink, fontSize: 18),),
Text(" RM ${a.price}", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown, fontSize: 16),
),
],
),
),
);
}
) : GridView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
padding: EdgeInsets.all(10),
itemCount: list.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 15,
crossAxisSpacing: 8
),
itemBuilder: (context,i){
final a = list[i];
return InkWell(
onTap: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) => ProductDetail(a)));
},
child: Container(
padding: EdgeInsets.all(10),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded
(child: Image.network("http://192.168.42.48/myapp/upload/"+ a.image,
width: 100.0,
fit: BoxFit.cover,
height: 180,
),
),
SizedBox(
height: 4,
),
Text("${a.attractionName}", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.pink, fontSize: 18),),
Text(" RM ${a.price}", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown, fontSize: 16),
),
],
),
),
);
}
),
//produk
],
),
)
);
}
}
Here is my menu user page and I want to put Search bar at the top of the page probably beside the logout button:

Related

Change radius of google search api with a dropdown button in flutter

I'm trying to get a list of veterinary clinics within a certain radius using google-maps-api. I am able to get the clinics in one radius but not getting any results when trying to add more radius' with a dropdownbutton. the radius' should be 2.5km,5km and 10km radius. this is my code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:vet_bookr/constant.dart';
import 'package:vet_bookr/models/vet_clinic.dart';
import 'package:vet_bookr/oScreens/vetMaps.dart';
import 'package:http/http.dart' as http;
import '../utils/constants.dart';
class PetClinicsPage extends StatefulWidget {
// PetClinicsPage(this.vetClinic);
const PetClinicsPage({super.key});
#override
State<PetClinicsPage> createState() => _PetClinicsPageState();
}
class _PetClinicsPageState extends State<PetClinicsPage> {
bool isLoading = true;
String dropdownvalue = 'in 2.5Kms';
var apiChanger = 0;
var apis = [
'in 2.5Kms',
'in 5Kms',
'in 10Kms',
];
#override
void initState() {
// TODO: implement initState
super.initState();
getTotalData();
}
late List<VetClinic>? vetClinic;
late GoogleMapController googleMapController;
static const String _kLocationServicesDisabledMessage =
'Location services are disabled.';
static const String _kPermissionDeniedMessage = 'Permission denied.';
static const String _kPermissionDeniedForeverMessage =
'Permission denied forever.';
static const String _kPermissionGrantedMessage = 'Permission granted.';
void _onMapCreated(GoogleMapController controller) {
googleMapController = controller;
}
Set<Marker> _markers = Set<Marker>();
Future<Position> determinePosition() async {
///Check if location is enabled
bool isLocationEnabled = await Geolocator.isLocationServiceEnabled();
if (!isLocationEnabled) {
return Future.error(_kLocationServicesDisabledMessage);
}
/**
* Request Location Permission
*/
await Geolocator.requestPermission();
///Check if the kind of permission we got
LocationPermission locationPermission = await Geolocator.checkPermission();
if (locationPermission == LocationPermission.denied) {
return Future.error(_kPermissionDeniedMessage);
}
if (locationPermission == LocationPermission.deniedForever) {
return Future.error(_kPermissionDeniedForeverMessage);
}
return Geolocator.getCurrentPosition();
}
Future<List<double>> getLatLng() async {
Position position = await determinePosition();
List<double> latLong = [position.latitude, position.longitude];
return latLong;
}
Future<void> getTotalData() async {
List<double> latLng = await getLatLng();
String vetsUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?keyword=vets&location=${latLng[0]},${latLng[1]}&radius=$apiChanger&type=veterinary_care&key=${Constants.apiKey}";
///Getting the data
final response = await http.get(Uri.parse(vetsUrl));
final Map<String, dynamic> data = jsonDecode(response.body);
print(data);
vetClinic = (data["results"] as List).map((vetJson) {
print(vetJson);
return VetClinic.fromJson(vetJson);
}).toList();
print(vetClinic);
/**
* Adding the markerss
*/
if (!mounted) return;
setState(() {
isLoading = false;
});
}
clinicTile(data) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VetsMaps(
vetClinic: data,
)));
},
child: Container(
margin: EdgeInsets.only(top: 0.03.sh),
width: 0.9.sw,
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.sp),
),
child: Padding(
padding: EdgeInsets.all(10.0.sp),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
data.name,
style: TextStyle(
fontSize: 16.sp,
fontWeight: FontWeight.w400,
color: Color(0xffFF8B6A)),
),
SizedBox(
height: 0.008.sh,
),
Text(
data.address,
style:
TextStyle(fontSize: 11.sp, fontWeight: FontWeight.w300),
),
SizedBox(
height: 0.005.sh,
),
Text(
data.timing ? "Currently Open" : "Currently Closed",
style: TextStyle(
fontSize: 15.sp,
color:
data.timing ? Colors.greenAccent : Colors.redAccent),
),
SizedBox(
height: 0.005.sh,
),
Container(
child: RatingBar.builder(
initialRating: data.rating,
direction: Axis.horizontal,
allowHalfRating: true,
itemCount: 5,
itemPadding: EdgeInsets.symmetric(horizontal: 1.0),
itemSize: 0.03.sh,
itemBuilder: (context, _) => Icon(
Icons.star,
color: Colors.amber,
),
onRatingUpdate: (rating) {
print(rating);
},
ignoreGestures: true,
),
)
],
),
),
),
),
);
}
void apisChanger() async {
if(dropdownvalue == apis[0]){
apiChanger = 2500;
}
if(dropdownvalue == apis[1]){
apiChanger = 5000;
}
if(dropdownvalue == apis[2]){
apiChanger = 10000;
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.black,
),
onPressed: () {
Navigator.pop(context);
},
),
),
backgroundColor: kBackgroundColor,
body: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.only(top: 10.sp, left: 10.sp, right: 10.sp),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// sBox(h: 10),
Row(
children: [
Padding(
padding: EdgeInsets.only(left: 10.0.sp, top: 15.sp),
child: Text(
'Veterinary Clinics Near Me',
style: TextStyle(color: Colors.deepOrange[300], fontSize: 22),
),
),
Container(
padding: EdgeInsets.only(top: 0.02.sh, left: 0.01.sw),
height: 0.04.sh,
child: DropdownButton(
value: dropdownvalue,
underline: SizedBox(),
icon: const Icon(Icons.keyboard_arrow_down),
items: apis.map((String items) {
return DropdownMenuItem(
value: items,
child: Text(items),
);
}).toList(),
onChanged: (String? newValue) {
apisChanger();
setState(() {
dropdownvalue = newValue!;
});
},
),
), ],
),
Divider(
thickness: 2,
color: Colors.deepOrange[300],
indent: 15,
endIndent: 10,
),
// sBox(h: 1),
isLoading
? Container(
width: 1.sw,
height: 0.7.sh,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 15.sp,
width: 15.sp,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Color(0xffFF8B6A),
),
),
],
),
)
: ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: vetClinic?.length,
itemBuilder: ((context, index) {
return clinicTile(vetClinic![index]);
}),
)
],
),
),
),
);
}
}
ive tried creating a variable which changes depending on the index of the array for the dropdown button but when i try this it doesnt work

Flutter - setState on a List of Widget (inner) not working or updating the main Widget status

I have a list of Widget that contains a list of 2 button and a text ..
and there is a list contains a counter for each one so when i press a button it will add +1 to the counter and it showing the new value after set status on onPressed !
the problem is that it is not changing the status of the Widget !
Example :
to be more clear :
the setState that located on List of Widget is not working !
i am bulding each itea of List of Widget using this void :
void constractor(int targetindex) async {
_bonestoiteams.add(0);
_iteamswigitcall.add(ListTile(
trailing: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
IconButton(
onPressed: () {
return setState(() {
_bonestoiteams[targetindex] = _bonestoiteams[targetindex] + 1;
});
},
icon: Icon(Icons.add),
color: Colors.green,
),
Text(
_bonestoiteams[targetindex].toString(),
textAlign: TextAlign.start,
textDirection: TextDirection.rtl,
style: TextStyle(
fontSize: 14, color: Colors.black, fontWeight: FontWeight.bold),
),
IconButton(
onPressed: () => setState(() {
_bonestoiteams[targetindex] = _bonestoiteams[targetindex] + 1;
print(_bonestoiteams[targetindex]);
}),
icon: Icon(Icons.remove),
color: Colors.red,
),
],
),
leading: LocalData.iteams_img_1[LocalData.iteams_trade_name
.indexOf(_silectediteams[targetindex])] ==
''
? Image(
fit: BoxFit.cover,
image: AssetImage('assets/img/medication.png'),
height: 60,
width: 60,
)
: Image(
fit: BoxFit.cover,
image: FileImage(File(LocalData.iteams_img_1[LocalData
.iteams_trade_name
.indexOf(_silectediteams[targetindex])])),
height: 60,
width: 60,
),
title: Text(
_silectediteams[targetindex].toString(),
textAlign: TextAlign.start,
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
));
}
what is not working is this line :
IconButton(
onPressed: () {
return setState(() {
_bonestoiteams[targetindex] = _bonestoiteams[targetindex] + 1;
});
},
icon: Icon(Icons.add),
color: Colors.green,
),
it is did add +1 ! but it not updating it directory i shold re Bulde or do something to showing the new value !
the mane class is :
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue[500],
title: Text("أضافة زيارة جديدة"),
centerTitle: true,
),
body: SingleChildScrollView(
child: Container(
margin: EdgeInsets.all(24),
child: SingleChildScrollView(
child: Form(
key: formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ductorlistnewserch(),
const SizedBox(
height: 13,
),
ductorlistpharmacy(),
const SizedBox(
height: 13,
),
iteamsselectiedlist(),
const SizedBox(
height: 13,
),
_buldenamefield1(),
const SizedBox(
height: 13,
),
_buldenamefield2(),
const SizedBox(
height: 13,
),
Column(
children: _iteamswigitcall,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
child: buildSubmit(),
padding: const EdgeInsets.all(8.0),
),
buildCancil(),
const SizedBox(
height: 10,
),
],
)
],
)),
),
)),
),
);
}
Full Code :
import 'dart:io';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:smart_bureau/components/LangData.dart';
import 'package:smart_bureau/components/LocalData.dart';
class AddVisist extends StatefulWidget {
#override
_AdVisit createState() => _AdVisit();
}
class _AdVisit extends State<AddVisist> {
#override
void initState() {
super.initState();
}
late String _ductorname;
late String _ductorstatus;
late String _clenicstatus;
late String _relatedpharmacy;
late List<String> _ductorrelatedpharmacy = [];
late List<String> _ductorlist = LocalData.doctor_name;
late List<String> _silectediteams = [];
late List<Widget> _iteamswigitcall = [];
late List<int> _bonestoiteams = [];
final controler1 = TextEditingController();
final controler2 = TextEditingController();
final controler3 = TextEditingController();
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
.....
cannot add the all mane class do to Max(30034)
if there is something not clear i can explane more in the commends ...
Edit :
Tryed to Bulde the iteams with ListView.builder but same problim !!
`ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
primary: false,
itemCount: _silectediteams.length, itemBuilder: (context, index) { return _iteamswigitcall[index];
}),`
Please try this below code mostly it should work
IconButton(
onPressed: () {
_bonestoiteams[targetindex] = _bonestoiteams[targetindex]++;
setState(() {});
},
icon: Icon(Icons.add),
color: Colors.green)

Scroll View Not Responding in flutter

My Scrollview not Responding, can someone tell what I am missing in code:
Please Suggest me how to add scroll view listener I'm beginner.
import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import '../main.dart';
import 'favourite_articles.dart';
import 'coin_system.dart';
class Settings extends StatefulWidget {
#override
_SettingsState createState() => _SettingsState();
}
class _SettingsState extends State<Settings> {
bool _notification = false;
ScrollController _controller;
#override
void initState() {
super.initState();
checkNotificationSetting();
}
checkNotificationSetting() async {
final prefs = await SharedPreferences.getInstance();
final key = 'notification';
final value = prefs.getInt(key) ?? 0;
if (value == 0) {
setState(() {
_notification = false;
});
} else {
setState(() {
_notification = true;
});
}
}
saveNotificationSetting(bool val) async {
final prefs = await SharedPreferences.getInstance();
final key = 'notification';
final value = val ? 1 : 0;
prefs.setInt(key, value);
if (value == 1) {
setState(() {
_notification = true;
});
} else {
setState(() {
_notification = false;
});
}
Future.delayed(const Duration(milliseconds: 500), () {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (BuildContext context) => MyHomePage()));
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
title: Text(
'More',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20,
fontFamily: 'Poppins'),
),
elevation: 5,
backgroundColor: Colors.white,
actions: <Widget>[
IconButton(
icon: Icon(Icons.mail),
color: Colors.black,
tooltip: 'Song Request',
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CoinSystem(),
),
);
})
],
),
body: Container(
decoration: BoxDecoration(color: Colors.white),
child: SingleChildScrollView(
controller: _controller,
scrollDirection: Axis.vertical,
child: Column(
children: <Widget>[
Container(
alignment: Alignment.center,
padding: EdgeInsets.fromLTRB(0, 20, 0, 10),
child: Image(
image: AssetImage('assets/icon.png'),
height: 50,
),
),
Container(
alignment: Alignment.center,
padding: EdgeInsets.fromLTRB(0, 10, 0, 20),
child: Text(
"Version 2.1.0 \n ",
textAlign: TextAlign.center,
style: TextStyle(height: 1.6, color: Colors.black87),
),
),
Divider(
height: 10,
thickness: 2,
),
//ListWheelScrollView(
ListView(
//itemExtent: 75,
shrinkWrap: true,
children: <Widget>[
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavouriteArticles(),
),
);
},
child: ListTile(
leading: Image.asset(
"assets/more/favourite.png",
width: 30,
),
title: Text('Favourite'),
subtitle: Text("See the saved songs"),
),
),
//Song Request Code
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CoinSystem(),
),
);
},
child: ListTile(
leading: Image.asset(
"assets/more/songrequest.png",
width: 30,
),
title: Text('Songs Request'),
subtitle: Text("Request your favourite songs"),
),
),
//Song Request Code End
ListTile(
leading: Image.asset(
"assets/more/notification.png",
width: 30,
),
isThreeLine: true,
title: Text('Notification'),
subtitle: Text("Change notification preference"),
trailing: Switch(
onChanged: (val) async {
await saveNotificationSetting(val);
},
value: _notification),
),
],
)
],
),
),
),
//),
);
//);
}
}
So, I have tried SingleChildScrollView, in that I have Container and Listview. But Listview doesn't response on scrolling action in landscape mode.
I have added ScrollController _controller; Do i have to create _controller class that listern the scrolling action?
In my understanding, you want to be able to get 2 scrolling. 1. using SingleChildScrollView and inside that Widget, you want to be able to scroll the bottom layer, thus you use ListView. To make it work, you have to place your ListView inside widget that has certain height. Example this implementation is:
SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: <Widget>[
SizedBox(child: Text('Upper scrollable'), height: 450),
Divider(
height: 10,
thickness: 2,
),
Container(
height: 350,
child: ListView(
shrinkWrap: true,
children: <Widget>[
Container(
color:Colors.red,
child: SizedBox(child: Text('Bottom scrollable'), height: 450),
),
],
),
)
],
),
),
If you don't want to use 2 scroll, don't use ListView inside SingleChildScrollView.
ListView cannot be wrapped with SingleChildScrollView remove it
surround ListView with Expanded Widget
try one of the two alternatives.

I have a problem with gridview display in flutter

You can see under my work, it is a lotto, a mini game in dart, user select 5 numbers and can validate his choice, the big 5 circles are the number selected but it is too too big and not render correctly in the blue rectangle :
I have a problem with the 5 Numbers in red just Under "Vos numéros", it is too big and i can't reduce the size in the code, it seems gridview adapt the size automatically, do you have any idea ?
import 'package:flutter/material.dart';
import 'dart:math';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:flutter_app/menu_member.dart';
import 'package:flutter_app/globals.dart' as globals;
class Lotto extends StatefulWidget {
#override
_LottoState createState() => new _LottoState();
}
class _LottoState extends State<Lotto> {
#override
void initState() {
super.initState();
}
var i=1;
var nb_num=49;
var no_select=[];
var no_a_select=5;
List<Color> colorList = List<Color>.generate(49, (int index) => Colors.lightBlue);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: new AppBar(
title: new Text('GRILLE DE LOTTO'),
),
body:
Center(
child: Column(
children: <Widget>[
Container(
width:400,
height:30,
margin: const EdgeInsets.only(top: 10.0),
child : new Text("Selectionnez 5 numéros",textAlign: TextAlign.center,style: TextStyle(fontSize: 30.0),),
),
Container(
width:400,
height:300,
child: new GridView.count(
crossAxisCount: 9,
padding: const EdgeInsets.all(30.0),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: new List<Widget>.generate(49, (index) {
return new GestureDetector(
onTap: () {
setState(() {
if (colorList[index] == Colors.lightBlue) {
if (no_select.length<no_a_select) {
colorList[index] = Colors.redAccent;
no_select.add(index+1);
}
else {
showDialog(
context: context,
builder: (BuildContext context){
return AlertDialog(
title: Text("INFORMATION"),
content: Text("Vous ne pouvez pas sélectionner plus de 5 numéros !!!"),
);
}
);
}
print(no_select);
}
else {
colorList[index] = Colors.lightBlue;
no_select.remove(index+1);
print(no_select);
}
});
},
child: Container(
child: ClipOval(
child: Container(
color: colorList[index],
height: 20.0,
width: 20.0,
child: Center(
child: new Text((index+1).toString(),
style: TextStyle(color: Colors.white, fontSize: 24),
textAlign: TextAlign.center),
),
),
),
),
);
}
),
),
),
Container(
width:400,
height:30,
margin: const EdgeInsets.only(top: 10),
child : new Text("Vos Numéros",textAlign: TextAlign.center,style: TextStyle(fontSize: 30.0),),
),
Container(
width:400,
height:80,
margin: const EdgeInsets.only(top: 10.0),
decoration: BoxDecoration(
border: Border.all(
color: Colors.lightBlueAccent,
width: 2,
),
borderRadius: BorderRadius.circular(12),
),
child:
getWidget()
),
Container(
width:300,
height:45,
margin: const EdgeInsets.only(top: 10.0),
child:
RaisedButton(
color: Colors.green,
textColor: Colors.white,
padding: EdgeInsets.fromLTRB(9, 9, 9, 9),
child: Text('TIRAGE ALEATOIRE'),
onPressed: () {
Select_numbers();
},
),
),
Container(
width:300,
height:45,
margin: const EdgeInsets.only(top: 10.0),
child:
RaisedButton(
color: Colors.green,
textColor: Colors.white,
padding: EdgeInsets.fromLTRB(9, 9, 9, 9),
child: Text('VALIDER VOTRE GRILLE'),
onPressed: () {
Valide_grille();
},
),
),
]
)
),
),
);
}
getWidget() {
if (no_select.length==0) {
return Text("Pas de numéros");
}
else {
return GridView.count(
crossAxisCount: 5,
padding: const EdgeInsets.all(10.0),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: new List<Widget>.generate(no_select.length, (index) {
return ClipOval(
child: Container(
color: Colors.red,
height: 20.0,
width: 20.0,
child: Center(
child: new Text((no_select[index].toString()),
style: TextStyle(color: Colors.white, fontSize: 24),
textAlign: TextAlign.center),
),
),
);
}
)
);
}
}
Select_numbers() {
setState(() {
var j = 1;
var num_sel;
var pos_sel;
no_select=[];
colorList=[];
colorList=List<Color>.generate(49, (int index) => Colors.lightBlue);
var rng = new Random();
List tab=[];
tab = List.generate(49, (int index) => index + 1);
print (tab);
while (j <= no_a_select) {
pos_sel = rng.nextInt(tab.length-1);
num_sel=tab[pos_sel];
no_select.add(num_sel);
colorList[num_sel-1] = Colors.redAccent;
tab.remove(num_sel);
print(tab);
j++;
}
print(no_select);
});
}
Future Valide_grille() async{
// For CircularProgressIndicator.
bool visible = false ;
// Showing CircularProgressIndicator.
setState(() {
visible = true ;
});
// SERVER LOGIN API URL
var url = 'https://www.easytrafic.fr/game_app/valide_lotto.php';
// Store all data with Param Name.
var data = {'id_membre':globals.id_membre, 'result':no_select};
print (data);
var grille_encode=jsonEncode(data);
print(grille_encode);
// Starting Web API Call.
var response = await http.post(url, body: grille_encode,headers: {'content-type': 'application/json','accept': 'application/json','authorization': globals.token});
print(response.body);
// Getting Server response into variable.
var message = json.decode(response.body);
// If the Response Message is Matched.
if(message == 'OK')
{
print('VALIDATION DE LA GRILLE OK');
// Hiding the CircularProgressIndicator.
setState(() {
visible = false;
});
}else{
// Hiding the CircularProgressIndicator.
setState(() {
visible = false;
});
// Showing Alert Dialog with Response JSON Message.
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text(message),
actions: <Widget>[
FlatButton(
child: new Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
}
It's because you put a Padding on your Gridview which make it scrollable
You can put the Padding to your ClipOval elements instead
return GridView.count(
crossAxisCount: 5,
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: new List<Widget>.generate(
no_select.length,
(index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ClipOval(
child: Container(
color: Colors.red,
height: 20.0,
width: 20.0,
child: Center(
child: new Text((no_select[index].toString()),
style: TextStyle(color: Colors.white, fontSize: 24), textAlign: TextAlign.center),
),
),
),
);
},
),
);

Add Search filed in App Bar with Navigation Drawer flutter

I am newbie into flutter. I have created a Navigation Drawer and it has multiple selection. In each seletion of drawer i have screen which consists of List of Data coming from server.
Now i want add Search Icon to Navigation Bar with Editfield to filter the list detials and update on the screen of any selected item from Navigation Drawer.
Please help me out.. and will be appreciated.
NavigationDrawer Screen
import 'package:flutter/material.dart';
import 'package:innovation_bridge/fragments/AnnouncementsScreen.dart';
import 'package:innovation_bridge/fragments/AttendeesScreen.dart';
import 'package:innovation_bridge/fragments/BookmarksScreen.dart';
import 'package:innovation_bridge/fragments/ExibitorsScreen.dart';
import 'package:innovation_bridge/fragments/HomeScreen.dart';
import 'package:innovation_bridge/fragments/InnovationsScreen.dart';
import 'package:innovation_bridge/fragments/MeetingsScreen.dart';
import 'package:innovation_bridge/fragments/PrivacyPolicyScreen.dart';
import 'package:innovation_bridge/fragments/ProgramScreen.dart';
import 'package:innovation_bridge/fragments/SpeedSessionScreen.dart';
import 'package:innovation_bridge/fragments/TermsConditionsScreen.dart';
import 'package:innovation_bridge/utils/Utils.dart';
class HomeDashboard extends StatefulWidget {
final drawerItems = [
new DrawerItem("Dashboard"),
new DrawerItem("Program"),
new DrawerItem("Exibitors"),
new DrawerItem("Innovations"),
new DrawerItem("Attendees"),
new DrawerItem("Speed Session"),
new DrawerItem("Bookmarks"),
new DrawerItem("Announcements"),
new DrawerItem("Privacy Policy"),
new DrawerItem("Terms & Conditions"),
new DrawerItem("Logout")
];
#override
_HomeDashboardState createState() => _HomeDashboardState();
}
class _HomeDashboardState extends State<HomeDashboard> {
int _selectedDrawerIndex = 0;
//Let's use a switch statement to return the Fragment for a selected item
_getDrawerFragment(int pos) {
switch (pos) {
case 0:
return new HomeScreen();
case 1:
return new ProgramScreen();
case 2:
return new ExibitorsScreen();
case 3:
return new InnovationsScreen();
case 4:
return new AttendeesScreen();
case 5:
return new SpeedSessionScreen();
case 6:
return new BookmarksScreen();
case 7:
return new AnnouncementsScreen();
case 8:
return new PrivacyPolicyScreen();
case 9:
return new TermsConditionsScreen();
default:
return new Text("Error");
}
}
//Let's update the selectedDrawerItemIndex the close the drawer
_onSelectItem(int index) {
setState(() => _selectedDrawerIndex = index);
//we close the drawer
Navigator.of(context).pop();
}
#override
Widget build(BuildContext context) {
List<Widget> drawerOptions = [];
//Let's create drawer list items. Each will have an icon and text
for (var i = 0; i < widget.drawerItems.length; i++) {
var d = widget.drawerItems[i];
drawerOptions.add(
ListTile(
title: new Text(d.title),
selected: i == _selectedDrawerIndex,
onTap: () => _onSelectItem(i),
)
);
}
//Let's scaffold our homepage
return new Scaffold(
appBar: new AppBar(
// We will dynamically display title of selected page
title: new Text(widget.drawerItems[_selectedDrawerIndex].title),
actions: <Widget>[
IconButton(
tooltip: 'Search',
icon: const Icon(Icons.search),
onPressed: (){
},
),
IconButton(
tooltip: 'Search',
icon: const Icon(Icons.filter_list),
onPressed: (){
},
)
],
),
// Let's register our Drawer to the Scaffold
drawer: SafeArea(
child: new Drawer(
child: new Column(
children: <Widget>[
Container(
color: Utils.hexToColor("#F24A1C"),
height: MediaQuery.of(context).size.height / 10,
width: MediaQuery.of(context).size.width,
child: Padding(
padding: EdgeInsets.only(left: 20),
child: Align(
alignment: Alignment.centerLeft,
child: Text('Menu', style: TextStyle(
fontSize: 18,
color: Colors.white
))
),
),
),
new Column(children: drawerOptions)
],
),
),
),
body: _getDrawerFragment(_selectedDrawerIndex),
);
}
}
//Let's define a DrawerItem data object
class DrawerItem {
String title;
IconData icon;
DrawerItem(this.title);
}
Here, in NavigationDrawer Screen, onclick of search icon TextField should enable and in List Screen filter should happen when user starting typing.
List Screen
import 'dart:math';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:innovation_bridge/detailScreens/ProgramDetailScreen.dart';
import 'package:innovation_bridge/dialogs/CommonMessageDialog.dart';
import 'package:innovation_bridge/utils/Utils.dart';
import 'package:table_calendar/table_calendar.dart';
class ProgramScreen extends StatefulWidget {
#override
_ProgramScreenState createState() => _ProgramScreenState();
}
class _ProgramScreenState extends State<ProgramScreen> {
var meteors = [
"Tunguska",
"Crab Pulsar",
"Geminga",
"Calvera",
"Vela X-1",
];
final String uri = 'https://jsonplaceholder.typicode.com/users';
Future<List<Users>> _fetchUsers() async {
print('## inside fetch user == ');
var response = await http.get(Uri.encodeFull(uri));
if (response.statusCode == 200) {
final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<Users> listOfUsers = items.map<Users>((json) {
return Users.fromJson(json);
}).toList();
return listOfUsers;
} else {
throw Exception('Failed to load internet');
}
}
CalendarController _calendarController;
#override
void initState() {
super.initState();
_calendarController = CalendarController();
}
#override
void dispose() {
_calendarController.dispose();
super.dispose();
}
void _onDaySelected(DateTime day, List events) {
print('## CALLBACK: _onDaySelected' +day.toIso8601String());
setState(() {
});
}
void _onVisibleDaysChanged(DateTime first, DateTime last, CalendarFormat format) {
print('CALLBACK: _onVisibleDaysChanged');
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Container(
color: Colors.grey[350],
child: _buildTableCalendar(),
),
Expanded(
child: StreamBuilder(
stream: Connectivity().onConnectivityChanged,
builder: (BuildContext context, AsyncSnapshot<ConnectivityResult> snapShot){
if (!snapShot.hasData) return Center(child: CircularProgressIndicator());
var result = snapShot.data;
switch (result) {
case ConnectivityResult.none:
print("no net");
return Center(child: Text("No Internet Connection! none "));
case ConnectivityResult.mobile:
return _listDetials();
case ConnectivityResult.wifi:
print("yes net");
return _listDetials();
default:
return Center(child: Text("No Internet Connection! default"));
}
},
),
)
],
),
);
}
FutureBuilder _listDetials(){
return FutureBuilder(
future: _fetchUsers(),
builder: (context, snapshot){
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasError){
return Text('${snapshot.error}');
}
else{
return ListView.builder(
itemCount: 5,
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index){
return Padding(
padding: EdgeInsets.fromLTRB(15.0, 10.0, 15.0, 4),
child: Container(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
GestureDetector(
onTap: (){
Navigator.push(context, MaterialPageRoute(
builder: (context) => ProgramDetailScreen()
));
},
child: Text('Program Activity Title', style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w400
)),
),
Padding(padding: EdgeInsets.only(top: 6)),
Row(
children: <Widget>[
Expanded(
flex: 2,
child: Text('Location Name', style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: Colors.blueAccent,
)),
),
Expanded(
flex: 2,
child: Align(
alignment: Alignment.centerRight,
child: Text('Start time - End time', style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: Colors.blueAccent,
))
),
)
],
),
Padding(padding: EdgeInsets.only(top: 6)),
Text('Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
),),
ExpansionTile(
title: Text(''),
trailing: Icon(
Icons.face,
size: 36.0,
),
children: <Widget>[
GridView.count(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
crossAxisCount: 3,
crossAxisSpacing: 5.0,
mainAxisSpacing: 5,
childAspectRatio: MediaQuery.of(context).size.width /
(MediaQuery.of(context).size.height / 4),
children: <Widget>[
GestureDetector(
onTap: (){
},
child: Container(
decoration: BoxDecoration(
border: Border.all(
width: 0.9
),
borderRadius: BorderRadius.all(
Radius.circular(5.0) // <--- border radius here
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(6, 5, 0, 0),
child: Text('Session Title',
softWrap: true,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold
)),
),
Padding(
padding: EdgeInsets.fromLTRB(6, 1, 0, 0),
child: Text('10:00 - 10:30',
softWrap: true,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 9
)),
),
Padding(
padding: EdgeInsets.fromLTRB(6, 1, 0, 0),
child: Text('Hall B',
softWrap: true,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 9
)),
),
],
),
),
)
]),
],
// onExpansionChanged: (bool expanding) => setState(() => this.isExpanded = expanding),
)
],
),
),
);
},
);
}
},
);
}
// Simple TableCalendar configuration (using Styles)
Widget _buildTableCalendar() {
return TableCalendar(
calendarController: _calendarController,
startingDayOfWeek: StartingDayOfWeek.monday,
headerVisible: true,
initialCalendarFormat: CalendarFormat.week, availableCalendarFormats: const { CalendarFormat.week: 'Week', },
calendarStyle: CalendarStyle(
selectedColor: Colors.deepOrange[400],
todayColor: Colors.deepOrange[200],
markersColor: Colors.brown[700],
outsideDaysVisible: true
),
headerStyle: HeaderStyle(
formatButtonTextStyle: TextStyle().copyWith(color: Colors.white, fontSize: 15.0),
formatButtonDecoration: BoxDecoration(
color: Colors.deepOrange[400],
borderRadius: BorderRadius.circular(10.0),
),
),
onDaySelected: _onDaySelected,
onVisibleDaysChanged: _onVisibleDaysChanged,
);
}
}
Widget createGridView(BuildContext context, List<String> cosmicBodies) {
//I will shuffle my data
cosmicBodies.shuffle();
// Then build my GridView and return it
return new GridView.builder(
itemCount: cosmicBodies.length,
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, mainAxisSpacing: 15.0),
itemBuilder: (BuildContext context, int index) {
return new GestureDetector(
child: new Card(
elevation: 5.0,
child: new Container(
alignment: Alignment.centerLeft,
margin: new EdgeInsets.only(top: 10.0, bottom: 10.0, left: 10.0),
child: new Text(cosmicBodies[index]),
),
),
);
});
}
class Users {
int id;
String name;
String username;
String email;
Users({
this.id,
this.name,
this.username,
this.email,
});
factory Users.fromJson(Map<String, dynamic> json) {
return Users(
id: json['id'],
name: json['name'],
email: json['email'],
username: json['username'],
);
}
}