I'm working on a flutter project and I made a GridView with images and titles but I want the title to be outside the square, If I make padding they give this error BOTTOM OVERFLOWED BY 32 PIXELS. Any help is highly appreciated.
this is my code :
Card makeDashboardItem(String title, String img, int index) {
return Card(
elevation: 2,
margin: const EdgeInsets.all(3),
child: Container(
child: InkWell(
onTap: () {
setState(() {
isLoading = true;
});
_splitScreen2(index);
},
child: Column(
children: <Widget>[
const SizedBox(height: 10),
Center(
child: Image.asset(img,
alignment: Alignment.center),
),
const SizedBox(height: 1),
Center(
child: Text(
title,
style: const TextStyle(
fontSize: 13,
color: Colors.black,
),
),
),
],
),
),
),
);
}
Check DartPad
The Main problem was overflow so we wrap Expanded widget on Image widget.
Nb: Remove Expanded widget from Image widget You can see the difference
CardWidget
class ItemWidget extends StatelessWidget {
var data;
ItemWidget(this.data, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 150,
child: Card(
child: Column(
children: [
Expanded(
child: Container(
height: 125,
child: Image.network(
data["Image"],
alignment: Alignment.center,
fit: BoxFit.cover,
),
),
),
Center(
child: Text(
data["Name"],
style: TextStyle(fontSize: 12),
))
],
),
),
);
}
}
Fullcode
import 'package:flutter/material.dart';
runApp(
MaterialApp(debugShowCheckedModeBanner: false, home: MyApp()),
);
}
class MyApp extends StatefulWidget {
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
var list = [
{
"Name": "ElectroniQues",
"Image":
"https://ecommerce.ccc2020.fr/wp-content/uploads/2020/10/electronic-gadgets.jpeg"
},
{
"Name": "Accessories",
"Image":
"https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/classic-accessories-1516305397.jpg"
},
{
"Name": "Hommes",
"Image":
"https://teja12.kuikr.com/is/a/c/880x425/gallery_images/original/cf5d08bff955e71.gif"
},
{
"Name": "Femmes",
"Image":
"https://cdn.pixabay.com/photo/2013/07/13/14/08/apparel-162192_1280.png"
},
{
"Name": "Enfants",
"Image": "https://images.indianexpress.com/2019/09/toys.jpg"
},
{
"Name": "Sunglasses",
"Image": "https://m.media-amazon.com/images/I/51zEsraniRL._UX569_.jpg"
},
{
"Name": "ElectroniQues",
"Image":
"https://ecommerce.ccc2020.fr/wp-content/uploads/2020/10/electronic-gadgets.jpeg"
},
{
"Name": "Accessories",
"Image":
"https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/classic-accessories-1516305397.jpg"
},
{
"Name": "Hommes",
"Image":
"https://teja12.kuikr.com/is/a/c/880x425/gallery_images/original/cf5d08bff955e71.gif"
},
{
"Name": "Femmes",
"Image":
"https://cdn.pixabay.com/photo/2013/07/13/14/08/apparel-162192_1280.png"
},
{
"Name": "Enfants",
"Image": "https://images.indianexpress.com/2019/09/toys.jpg"
},
{
"Name": "Sunglasses",
"Image": "https://m.media-amazon.com/images/I/51zEsraniRL._UX569_.jpg"
},
];
var column = Column(mainAxisAlignment: MainAxisAlignment.start, children: [
...list.map((e) {
return GestureDetector(onTap:(){},child: ItemWidget(e));
}).toList()
]);
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SafeArea(
child: Row(
children: [
SideWidget(),
Expanded(
child: Scaffold(
bottomNavigationBar: buildBottomNavigationBar(),
body: Padding(
padding: const EdgeInsets.only(top: 18.0),
child:
// column
GridView.count(
crossAxisCount: 3,
mainAxisSpacing: 2,
crossAxisSpacing: 2,
children: [
...list.map((e) {
return InkWell(onTap:(){},child: ItemWidget(e));
}).toList()
],
),
),
),
),
],
),
),
);
}
BottomNavigationBar buildBottomNavigationBar() {
return BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: 0,
selectedItemColor: Colors.amber[800],
onTap: (v) {},
);
}
}
class SideWidget extends StatelessWidget {
const SideWidget({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Material(
child: Container(
width: 63,
color: Colors.white,
child: ListView(
children: [
...[
Icons.headset,
Icons.pets,
Icons.watch,
Icons.color_lens,
Icons.today
]
.map((e) => Padding(
padding: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 4.0),
child: TextButton(
onPressed: () {},
child: Icon(
e,
color: Colors.blueGrey,
size: 40,
),
),
))
.toList()
],
),
),
);
}
}
class ItemWidget extends StatelessWidget {
var data;
ItemWidget(this.data, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 150,
child: Card(
child: Column(
children: [
Expanded(
child: Container(
height: 125,
child: GridTile(
// footer:Text(data["Name"]) ,
child: Image.network(
data["Image"],
alignment: Alignment.center,
fit: BoxFit.cover,
),
),
),
),
Center(
child: Text(
data["Name"],
style: TextStyle(fontSize: 12),
))
],
),
),
);
}
}
GridView children size depends on aspect ratio, which is 1 by default. In your case, image is not getting proper height.
For your case, You can use fit on Image.asset.
Image.asset(
"",
fit: BoxFit.cover, // or the .width or the one you prefer
),
Also you can try GridTile
GridTile(
child: Image.asset(
"",
fit: BoxFit.cover,
),
footer: Text("title"),
),
More about GridTile and BoxFit.
Firstly, the way you have created the widget tree is not proper.
Currently, you have
Card -> Container -> Column -> 1. Image
2. Text
If you want the title to be out of your square (Card), it should be:
Column -> 1. Card -> Image
2. Text
This way your title will be out of the card.
Related
I am developing an app with flutter and I am getting an error about height.
I have a listview.separated and I have a SingleChildScrollView. I am getting flex error.
This is my file to align widgets inside Scaffold and SafeArea. I have a file for runApp but it is not important for the question.
class ProfilePageC extends StatelessWidget {
const ProfilePageC({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
AboutTopBarW(), // It has not listview
ImageFieldW(), // It has no listview
PercentsW(), //It has no listview
HomeArticleList2W() //It has a listview.separated
],
),
),
),
);
}
}
this is my file for listview.separated widget.
class HomeArticleList2W extends ConsumerWidget {
const HomeArticleList2W({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
final futureCatFacts = ref.watch(multiFutureArticleProvider);
return Expanded(
child: futureCatFacts.when(
loading: () => const ShimmerHomeW(),
error: (err, stack) => Text('Error: $err'),
data: (data) {
final decodedData = json.decode(data.body);
return ListView.separated(
separatorBuilder: (BuildContext context, int index) {
if (index % 3 == 0) {
return const Divider();
}
return const Divider();
},
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: decodedData.length ,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.only(
left: 20,
right: 20,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.network(
decodedData[index]['largeImage'].toString(),
fit: BoxFit.cover,
height: 70,
width: 70,
)),
const SizedBox(
width: 10,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
decodedData[index]['title'],
style: const TextStyle(
fontSize: 15, fontWeight: FontWeight.bold),
),
const SizedBox(
height: 5,
),
Row(
children: [
const Icon(
Icons.av_timer_sharp,
size: 20,
),
Text(decodedData[index]['date']),
],
),
],
),
),
const SizedBox(
width: 5,
),
const Icon(Icons.bookmark_border),
],
),
);
},
);
},
),
);
}
}
There is no error when I erase HomeArticleList2W() from the SingleChildScrollView. Therefore I thnink the error consist of the listview.separated.
How to solve this problem.
Remove the expanded widget and add mainAxisSize min
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
decodedData[index]['title'],
style: const TextStyle(
fontSize: 15, fontWeight: FontWeight.bold),
),
const SizedBox(
height: 5,
),
Row(
children: [
const Icon(
Icons.av_timer_sharp,
size: 20,
),
Text(decodedData[index]['date']),
],
),
],
),
Can anyone advise me how to design a very specific Side menu in flutter.
It has 2 states
Collapsed (Small but icons are visible.)
Expanded (Big, Icons and text)
When collapsed it is like a Navigation rail. Only icons visible.
But when expanded, it should behave like Navigation drawer. It should blur the rest of the screen, and on click outside of it it should collapse back.
I would appreciate any help.
Thank you
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
bool is_expanded = false;
int selectedPage = 1;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.transparent,
body: Row(
children: [
Stack(
children: <Widget>[
Container(
color: Colors.transparent,
margin: EdgeInsets.only(left: 120),
width: MediaQuery.of(context).size.width - 120,
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 1, sigmaY: 1),
child: Opacity(
opacity: is_expanded ? 0.3 : 1,
child: Listener(
onPointerDown: (v) {
if (is_expanded) {
is_expanded = false;
setState(() {});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Click blocked'),
),
);
}
},
child: AbsorbPointer(
absorbing: is_expanded,
child: Row(
children: [
Expanded(
child: Container(
color: Colors.white,
child: PageHolder(selectedPage),
),
),
],
),
),
),
),
),
),
AnimatedContainer(
duration: Duration(milliseconds: 120),
height: double.infinity,
width: is_expanded ? 240 : 120,
color: Colors.blueGrey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 20),
Row(
mainAxisSize: MainAxisSize.min,
children: const [
Text(
'Custom drawer',
style: TextStyle(
color: Colors.white,
),
),
],
),
const SizedBox(height: 20),
InkWell(
onTap: () {
setState(() => is_expanded = !is_expanded);
},
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"App",
style: TextStyle(
color: Colors.white,
),
),
Icon(
is_expanded ? Icons.arrow_right : Icons.arrow_left,
color: Colors.white,
)
],
),
),
const SizedBox(height: 20),
InkWell(
onTap: () {
selectedPage = 1;
is_expanded = false;
setState(() {});
},
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
"Page 1",
style: TextStyle(
color: Colors.white,
),
),
],
),
),
const SizedBox(height: 20),
InkWell(
onTap: () {
selectedPage = 2;
is_expanded = false;
setState(() {});
},
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
"Page 2",
style: TextStyle(
color: Colors.white,
),
),
],
),
),
],
),
),
],
),
],
),
);
}
PageHolder(selectedPage) {
switch (selectedPage) {
case 1:
{
return Page1();
}
case 2:
{
return Page2();
}
default:
{
return Page1();
}
}
}
}
class Page1 extends StatefulWidget {
const Page1({Key? key}) : super(key: key);
#override
State<Page1> createState() => _Page1State();
}
class _Page1State extends State<Page1> {
#override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Page 1 content',
style: TextStyle(fontSize: 32),),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Test click'),
),
);
},
child: const Text('Test click'))
],
),
);
}
}
class Page2 extends StatefulWidget {
const Page2({Key? key}) : super(key: key);
#override
State<Page2> createState() => _Page2State();
}
class _Page2State extends State<Page2> {
#override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Page 2 content',
style: TextStyle(fontSize: 32),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Test click'),
),
);
},
child: const Text('Test click'))
],
),
);
}
}```
Solution ^^
include NavigationRail widget in IntrinsicWidth widget
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
),
drawer: _NavigationRailExample(),
body: Container(),
);
}
}
class _NavigationRailExample extends StatefulWidget {
const _NavigationRailExample({Key? key}) : super(key: key);
_NavigationRailExampleState createState() => _NavigationRailExampleState();
}
class _NavigationRailExampleState extends State<_NavigationRailExample> {
int _selectedIndex = 0;
bool extended =false;
Widget build(BuildContext context) {
return SafeArea(
child: IntrinsicWidth(
child: NavigationRail(
selectedIndex: _selectedIndex,
destinations: _buildDestinations(),
extended: extended,
onDestinationSelected: (int index) {
setState(() {
_selectedIndex = index;
});
},
),
),
);
}
List<NavigationRailDestination> _buildDestinations() {
return [
NavigationRailDestination(
icon: InkWell(
onTap: () {
setState(() =>
extended = !extended);
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text("App"),
Icon(extended ? Icons.arrow_right : Icons.arrow_left)
],
),
),
label: Container(width: 0,) ,
),
NavigationRailDestination(
icon: Icon(Icons.home),
label: Text('Home'),
),
NavigationRailDestination(
icon: Icon(Icons.favorite),
label: Text('Favorites'),
),
NavigationRailDestination(
icon: Icon(Icons.logout),
label: Text('Logout'),
),
];
}
}
im going to change colors Container when
click on GestureDetector but nothing change... .
like this image:and im click on vector men and women..
and nothing change...i use linear gradiant and List of color please help me to solve this problem
import 'package:flutter/material.dart';
import 'icon_content.dart';
import 'reusable_card.dart';
const BottomContainerHeight = 80.0;
List<Color> inactiveCardColoursFemale = [Color(0xFF42A5F5), Color(0xFF039BE5)];
List<Color> activeCardColoursFemale = [Color(0xFF303F9F), Color(0xFF283593)];
List<Color> inactiveCardColoursMale = [Color(0xFFFBC02D), Color(0xFFFFB300)];
List<Color> activeCardColoursMale = [Color(0xFFFF6F00), Color(0xFFE65100)];
enum Gender {
male,
female,
}
class InputPage extends StatefulWidget {
const InputPage({Key? key}) : super(key: key);
#override
_InputPageState createState() => _InputPageState();
}
class _InputPageState extends State<InputPage> {
Gender selectedGender = Gender.female;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.deepOrangeAccent,
title: const Text("Iman Bmi"),
centerTitle: true,
),
body: Column(
children: [
Expanded(
child: Expanded(
child: Row(
children: [
Expanded(
child: GestureDetector(
onTap: () {
setState(() {
selectedGender = Gender.female;
});
},
child: ReusableCard(
colour: selectedGender == Gender.female
? inactiveCardColoursFemale
: activeCardColoursFemale,
cardChild: IconContent(
svgPicture: 'assets/2.svg',
label: 'women',
),
),
),
),
Expanded(
child: GestureDetector(
onTap: () {
setState(() {
selectedGender = Gender.male;
});
},
child: ReusableCard(
colour: selectedGender == Gender.male
? activeCardColoursMale
: inactiveCardColoursMale,
cardChild: IconContent(
svgPicture: 'assets/3.svg',
label: 'men',
)),
),
),
],
),
)),
Expanded(
child: ReusableCard(
colour: [Colors.deepPurple, Colors.purple],
//colour: Color(0xFF65E655),
cardChild: Row(
children: [],
),
),
),
Expanded(
child: Row(
children: [
Expanded(
child: ReusableCard(
colour: [Colors.teal, Colors.tealAccent],
//colour: Color(0xFF65E655),
cardChild: Column(
children: [],
),
),
),
Expanded(
child: ReusableCard(
colour: [Colors.amber, Colors.yellow],
//colour: Color(0xFF65E655),
cardChild: Column(
children: [],
),
),
),
],
)),
Container(
margin: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: BottomContainerHeight,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [Colors.deepOrange, Colors.deepOrangeAccent]),
borderRadius: BorderRadius.circular(10.0)),
),
],
),
);
}
}
and My Reusable Card Class Code: i use to linear Gradiant and List of color
import 'package:flutter/material.dart';
class ReusableCard extends StatelessWidget {
ReusableCard({required this.colour, required this.cardChild});
//required this.colour
final List<Color> colour;
final Widget cardChild;
#override
Widget build(BuildContext context) {
return Container(
child: cardChild,
margin: EdgeInsets.all(10.0),
decoration: BoxDecoration(
//color: colour,
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: colour,
),
//Color(0xFF65E655)
borderRadius: BorderRadius.circular(10.0)),
);
}
}
Removing the first Expanded widget inside your Column should fix your issue.
// Change this
Column(children: [Expanded(child: Expanded(child: Row()))])
// to this
Column(children: [Expanded(child: Row())])
how can I make tabs behind actions in appBar ?like this ! photo
, my code look like this and I've tried to put tabs on leading
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
actions: [
IconButton(onPressed: () {}, icon: Icon(Icons.home)),
IconButton(onPressed: () {}, icon: Icon(Icons.search)),
IconButton(onPressed: () {}, icon: Icon(Icons.archive)),
],
leadingWidth: double.maxFinite,
leading: TabBar(
indicatorSize: TabBarIndicatorSize.tab,
tabs: [
Tab(text: "Pending"),
Tab(text: "Delivered"),
],
),
),
body: TabBarView(
children: [
Tab(text: "Pending"),
Tab(text: "Delivered"),
],
),
),
);
}
}
and here how it's the output look like =>
what if you put the tab in title instead of leading:
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
actions: [
IconButton(onPressed: () {}, icon: Icon(Icons.home)),
IconButton(onPressed: () {}, icon: Icon(Icons.search)),
IconButton(onPressed: () {}, icon: Icon(Icons.archive)),
],
title: TabBar(
indicatorSize: TabBarIndicatorSize.tab,
tabs: [
Tab(text: "Pending"),
Tab(text: "Delivered"),
],
),
),
body: TabBarView(
children: [
Tab(text: "Pending"),
Tab(text: "Delivered"),
],
),
),
);
}
}
You can add the carousel_slider dependency. To get it you can visit pub.dev and search for carousel_slider or here's a link https://pub.dev/packages/carousel_slider. I hope this helps )
//example image
final List<String> imgList = [
'https://images.unsplash.com/photo-1520342868574-5fa3804e551c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=6ff92caffcdd63681a35134a6770ed3b&auto=format&fit=crop&w=1951&q=80',
'https://images.unsplash.com/photo-1522205408450-add114ad53fe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=368f45b0888aeb0b7b08e3a1084d3ede&auto=format&fit=crop&w=1950&q=80',
'https://images.unsplash.com/photo-1519125323398-675f0ddb6308?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=94a1e718d89ca60a6337a6008341ca50&auto=format&fit=crop&w=1950&q=80',
'https://images.unsplash.com/photo-1523205771623-e0faa4d2813d?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=89719a0d55dd05e2deae4120227e6efc&auto=format&fit=crop&w=1953&q=80',
'https://images.unsplash.com/photo-1508704019882-f9cf40e475b4?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=8c6e5e3aba713b17aa1fe71ab4f0ae5b&auto=format&fit=crop&w=1352&q=80',
'https://images.unsplash.com/photo-1519985176271-adb1088fa94c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=a0c8d632e977f94e5d312d9893258f59&auto=format&fit=crop&w=1355&q=80'
];
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHome(),
);
}
}
class MyHome extends StatefulWidget {
const MyHome({Key? key}) : super(key: key);
#override
State<MyHome> createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
final List<Widget> imageSliders = imgList
.map((item) => Container(
child: Container(
margin: EdgeInsets.all(5.0),
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
child: Stack(
children: <Widget>[
Image.network(item, fit: BoxFit.cover, width: 1000.0),
Positioned(
bottom: 0.0,
left: 0.0,
right: 0.0,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromARGB(200, 0, 0, 0),
Color.fromARGB(0, 0, 0, 0)
],
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
),
),
padding: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 20.0),
// child: Text(
// 'No. ${imgList.indexOf(item)} image',
// style: TextStyle(
// color: Colors.white,
// fontSize: 20.0,
// fontWeight: FontWeight.bold,
// ),
// ),
),
),
],
)),
),
))
.toList();
#override
Widget build(BuildContext context) {
int _current = 0;
final CarouselController _controller = CarouselController();
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
actions: [
IconButton(onPressed: () {}, icon: Icon(Icons.home)),
IconButton(onPressed: () {}, icon: Icon(Icons.search)),
IconButton(onPressed: () {}, icon: Icon(Icons.archive)),
],
leadingWidth: double.maxFinite,
leading: TabBar(
indicatorSize: TabBarIndicatorSize.tab,
tabs: [
Tab(text: "Pending"),
Tab(text: "Delivered"),
],
),
),
body:Container(
child: Column(
mainAxisAlignment:MainAxisAlignment.start,
children: [
CarouselSlider(
items: imageSliders,
carouselController: _controller,
options: CarouselOptions(
height: 200,
scrollDirection: Axis.horizontal,
autoPlay: true,
enlargeCenterPage: true,
aspectRatio: 2.0,
viewportFraction: 1,
onPageChanged: (index, reason) {
setState(() {
_current = index;
});
}),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: imgList.asMap().entries.map((entry) {
return GestureDetector(
onTap: () => _controller.animateToPage(entry.key),
child: Container(
width: 12.0,
height: 12.0,
margin: EdgeInsets.symmetric(vertical: 1.0, horizontal: 4.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: (Theme.of(context).brightness == Brightness.dark
? Colors.white
: Colors.black)
.withOpacity(_current == entry.key ? 0.9 : 0.4)),
),
);
}).toList(),
),
]),
),
),
);
}
}
I want to add a scroll controller to the pageview (which can scroll horizontally as well as vertically) so that I can hide the content like appbar that are above it when I scroll down the contents of the pageview.
I tried adding the Singlechildscrollview but it doesn't work properly don't know why.
It doesn't register the up down scrolls.
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int currentPage = 0;
bool isScrollingDown = false;
PageController _controller = PageController(
initialPage: 0,
);
ScrollController _scrollController;
#override
void initState() {
super.initState();
_initImages();
_scrollController = ScrollController();
_scrollController.addListener(() {
if (_scrollController.position.userScrollDirection ==
ScrollDirection.reverse) {
if (!isScrollingDown) {
setState(() {
isScrollingDown = true;
});
print(isScrollingDown);
}
}
if (_scrollController.position.userScrollDirection ==
ScrollDirection.forward) {
if (isScrollingDown) {
setState(() {
isScrollingDown = false;
});
print(isScrollingDown);
}
}
});
}
#override
void dispose() {
_controller.dispose();
_scrollController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
),
body: Container(
color: Colors.black,
child: Column(
children: [
AnimatedContainer(
height: isScrollingDown ? 0 : height * 0.25,
duration: Duration(milliseconds: 400),
child: Column(
children: [
CircleAvatar(
backgroundImage: AssetImage("assets/profile.jpg"),
),
SizedBox(
height: 10,
),
Text(
"Samantha Smith",
style: profileText(),
),
Text(
"#imsamanthasmith",
style: profileValues(),
),
SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
Text(
"1.2m",
style: profileStats(),
),
Text(
"Liked",
style: profileValues(),
)
],
),
Column(
children: [
Text(
"12.8k",
style: profileStats(),
),
Text(
"Followers",
style: profileValues(),
)
],
),
Column(
children: [
Text(
"1.9k",
style: profileStats(),
),
Text(
"Following",
style: profileValues(),
)
],
),
],
)
],
),
),
SizedBox(
height: 30,
),
Column(
children: [
Container(
decoration: BoxDecoration(
color: Colors.grey[900],
borderRadius: BorderRadius.only(
topRight: Radius.circular(20),
topLeft: Radius.circular(20))),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
IconButton(
icon: currentPage == 0
? Icon(Icons.grid_on_rounded)
: Icon(Icons.grid_view),
onPressed: () {
_controller.animateToPage(0,
duration: Duration(milliseconds: 50),
curve: Curves.bounceOut);
},
),
IconButton(
icon: currentPage == 1
? Icon(Icons.favorite)
: Icon(Icons.favorite_border),
onPressed: () {
_controller.animateToPage(1,
duration: Duration(milliseconds: 50),
curve: Curves.bounceOut);
},
),
IconButton(
icon: currentPage == 2
? Icon(Icons.bookmark)
: Icon(Icons.bookmark_outline),
onPressed: () {
_controller.animateToPage(2,
duration: Duration(milliseconds: 50),
curve: Curves.bounceOut);
},
),
],
),
),
],
),
Expanded(
child: PageView(
physics: BouncingScrollPhysics(),
controller: _controller,
onPageChanged: (value) {
setState(() {
currentPage = value;
});
},
children: [
Page1(foodImages),
Page2(danceImages),
Page3(lolImages),
],
),
)
],
),
),
);
}
}
You can use CustomScrollView instead of using Scaffold, so you can use SliverAppBar which does have properties which you want to do like hiding/appearing on scroll etc.
Here is the link of detailed information about SliverAppBar https://api.flutter.dev/flutter/material/SliverAppBar-class.html
Official doc from Flutter about implementing SliverAppBar here https://flutter.dev/docs/cookbook/lists/floating-app-bar#2-use-sliverappbar-to-add-a-floating-app-bar