is there any way to stop gesture bubbling in flutter? - flutter

I have TabBarView with 3 children, one of them I have a container which has an onPanUpdate gesture.
When I am trying to move container tab bar onHorizontalDragUpdate calls and tab bar changes tab but not container.
Is there any way to prevent onHorizontalDragUpdate if I taped on a container like stoppropagation in javascript?
TabBarView(
controller: _tabController,
children: [
Container(
color: Colors.red,
),
TabWithDragableContainer(),
Container(
color: Colors.blue,
),
],
)

You could disable the gestures for all the tabs by specifying physics: NeverScrollableScrollPhysics() inside TabBarView.
Minimal Working Example
This example has three tabs:
Basic Tab
Tab with Draggable Widget
Tab with onPan GestureDetector
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
);
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
),
body: TabBarView(
physics: NeverScrollableScrollPhysics(),
children: [
Icon(Icons.directions_car),
_ContainerWithDraggable(),
_ContainerWithPanGesture(),
],
),
),
);
}
}
class _ContainerWithDraggable extends HookWidget {
#override
Widget build(BuildContext context) {
final _offset = useState(Offset(100, 100));
return Stack(
children: [
Container(color: Colors.amber.shade100),
Positioned(
top: _offset.value.dy,
left: _offset.value.dx,
child: Draggable(
onDragUpdate: (details) => _offset.value += details.delta,
feedback: _Circle(),
child: _Circle(),
),
),
],
);
}
}
class _ContainerWithPanGesture extends HookWidget {
#override
Widget build(BuildContext context) {
final _offset = useState(Offset(100, 100));
final _previousOffset = useState<Offset>(null);
final _referenceOffset = useState<Offset>(null);
return Stack(
children: [
GestureDetector(
onPanStart: (details) {
_previousOffset.value = _offset.value;
_referenceOffset.value = details.localPosition;
},
onPanUpdate: (details) => _offset.value = _previousOffset.value +
details.localPosition -
_referenceOffset.value,
child: Container(color: Colors.amber.shade100),
),
Positioned(
top: _offset.value.dy,
left: _offset.value.dx,
child: _Circle(),
),
],
);
}
}
class _Circle extends StatelessWidget {
const _Circle({
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
width: 50,
height: 50,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.brown, width: 5.0),
),
);
}
}

Related

how to make a stack widget take full screen on ios in flutter

I am trying to make an audio player app,
and I want to make the player screen fit the whole screen size.
However, the padding at the top and at the bottom doesn't help.
I tried to remove the SafeArea from bottomNavigationBar and other widgets and it didn't work.
How can I handle this?
Image of the player:
(the gray color padding doesn't let the image stretch to the end)
the code of the player:
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: const Color(0xff1c1c1e),
body: GetBuilder<OverlayHandler>(
builder: (getContext) {
if (!Get.find<OverlayHandler>().inPipMode) {
return Stack(
children:[
Container(...)
]
); // player at full screen
} else {
return Stack(...); // player at PiP mode
}
}
)
);
}
the code of the main screen widget:
Widget build(BuildContext context) {
return GetBuilder<NavigationController>(
builder: (controller) {
return Scaffold(
body: SafeArea(
// bottom option of this SafeArea doesn't affect the player size
child: IndexedStack(
index: controller.tabIndex,
children: const [
...
],
),
),
bottomNavigationBar: SafeArea(
// bottom option of this SafeArea doesn't affect the player size
child: SizedBox(
height: 80,
child: BottomNavigationBar(
items: [
...
],
),
),
),
);
}
);
}
}
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
#override
State<HomeScreen> createState() => _HomeScreenState();
}
TextEditingController controller = TextEditingController();
bool hasHash = false;
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Container(
height: double.infinity,
decoration: const BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(
"https://cdn.pixabay.com/photo/2016/09/10/11/11/musician-1658887_1280.jpg",
),
),
),
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
height: 300,
width: double.infinity,
color: Colors.black.withOpacity(.7),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Icon(
Icons.skip_previous_rounded,
size: 55,
color: Colors.white,
),
Icon(
Icons.play_circle_fill_rounded,
size: 110,
color: Colors.white,
),
Icon(
Icons.skip_next_rounded,
size: 55,
color: Colors.white,
),
],
),
),
),
],
),
);
}
}
Android screenshot
iOS screenshot
Try removing the Scaffold()'s background color and add extendBody: true, or set the height of the container to height: double.infinity, or inside the stack just add and empty container with height as height: double.infinity,

How to make Column scrollable when overflowed but use expanded otherwise

I am trying to achieve an effect where there is expandable content on the top end of a sidebar, and other links on the bottom of the sidebar. When the content on the top expands to the point it needs to scroll, the bottom links should scroll in the same view.
Here is an example of what I am trying to do, except that it does not scroll. If I wrap a scrollable view around the column, that won't work with the spacer or expanded that is needed to keep the bottom links on bottom:
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatefulWidget {
#override
State<MyWidget> createState() {
return MyWidgetState();
}
}
class MyWidgetState extends State<MyWidget> {
List<int> items = [1];
#override
Widget build(BuildContext context) {
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: const Icon(Icons.add),
onPressed: () {
setState(() {
items.add(items.last + 1);
});
},
),
IconButton(
icon: const Icon(Icons.delete),
onPressed: () {
setState(() {
if (items.length != 1) items.removeLast();
});
},
),
],
),
for (final item in items)
MyAnimatedWidget(
child: SizedBox(
height: 200,
child: Center(
child: Text('Top content item $item'),
),
),
),
Spacer(),
Container(
alignment: Alignment.center,
decoration: BoxDecoration(border: Border.all()),
height: 200,
child: Text('Bottom content'),
)
],
);
}
}
class MyAnimatedWidget extends StatefulWidget {
final Widget? child;
const MyAnimatedWidget({this.child, Key? key}) : super(key: key);
#override
State<MyAnimatedWidget> createState() {
return MyAnimatedWidgetState();
}
}
class MyAnimatedWidgetState extends State<MyAnimatedWidget>
with SingleTickerProviderStateMixin {
late AnimationController controller;
#override
initState() {
controller = AnimationController(
value: 0, duration: const Duration(seconds: 1), vsync: this);
controller.animateTo(1, curve: Curves.linear);
super.initState();
}
#override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: controller,
builder: (context, child) {
return SizedBox(height: 200 * controller.value, child: widget.child);
});
}
}
I have tried using a global key to get the size of the spacer and detect after rebuilds whether the spacer has been sized to 0, and if so, re-build the entire widget as a list view (without the spacer) instead of a column. You also need to listen in that case for if the size shrinks and it needs to become a column again, it seemed to make the performance noticeably worse, it was tricky to save the state when switching between column/listview, and it seemed not the best way to solve the problem.
Any ideas?
Try implementing this solution I've just created without the animation you have. Is a scrollable area at the top and a persistent footer.
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
home: SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text("My AppBar"),
),
body: Column(
children: [
Expanded(
child: SingleChildScrollView(
child: Column(
children: [
// Your scrollable widgets here
Container(
height: 100,
color: Colors.green,
),
Container(
height: 100,
color: Colors.blue,
),
Container(
height: 100,
color: Colors.red,
),
],
),
),
),
Container(
child: Text(
'Your footer',
),
color: Colors.blueGrey,
height: 200,
width: double.infinity,
)
],
),
),
),
);
}
}

Flutter: Long Press on picture to get zoomed preview like Instagram

so I am currently having a grid of pictures and I want to implement a feature from instagram: If you longPress on one of the pictures, you get a a larger version of that picture appearing in the middle of the screen. If you stop pressing, the image dissapears.
I don't really need the code for that, but I just can't think of which widgets I should use.
Is there maybe a package for something like this? If not then how can I do it with Flutter standard widgets? Maybe using a dialog that appears on the longPress ?
Here's the improved vewrsion that resembles the same exact UX as of Instagram with blurred background.
We can achieve this using a combination of Stateful Widget, Stack and BackdropFliter, here is the sample code -
import 'dart:ui';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Counter Demo',
theme: ThemeData.light(),
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blueGrey,
centerTitle: true,
title: Text("Demo App"),
),
body: Stacked(),
),
);
}
}
class Stacked extends StatefulWidget {
#override
_StackedState createState() => _StackedState();
}
class _StackedState extends State<Stacked> {
final List<String> images = [
"1.jpg",
"2.jpg",
"3.jpg",
"4.jpg",
"5.jpg",
"6.jpg",
"7.jpg",
"8.jpg",
"9.jpg",
"10.jpg",
];
bool _showPreview = false;
String _image = "assets/images/1.jpg";
#override
Widget build(BuildContext context) {
return SafeArea(
child: Stack(
children: [
GridView.builder(
itemCount: images.length,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onLongPress: () {
setState(() {
_showPreview = true;
_image = "assets/images/${images[index]}";
});
},
onLongPressEnd: (details) {
setState(() {
_showPreview = false;
});
},
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Card(
elevation: 4,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0),
),
clipBehavior: Clip.hardEdge,
child: Image.asset("assets/images/${images[index]}"),
),
),
);
},
),
if (_showPreview) ...[
BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
),
child: Container(
color: Colors.white.withOpacity(0.6),
),
),
Container(
child: Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.asset(
_image,
height: 300,
width: 300,
),
),
),
),
],
],
));
}
}
This is just a baseline example and there are endless possibilities you can modify this to achieve behavior you want.
Another simple way is we can build this by using StatefulWidget and IndexedStack -
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Counter Demo',
theme: ThemeData.light(),
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blueGrey,
centerTitle: true,
title: Text("Demo App"),
),
body: Body(),
),
);
}
}
class Body extends StatefulWidget {
#override
_BodyState createState() => _BodyState();
}
class _BodyState extends State<Body> {
final List<String> images = [
"1.jpg",
"2.jpg",
"3.jpg",
"4.jpg",
"5.jpg",
"6.jpg",
"7.jpg",
"8.jpg",
"9.jpg",
"10.jpg",
];
int _index = 0;
String _image = "assets/images/1.jpg";
#override
Widget build(BuildContext context) {
return SafeArea(
child: IndexedStack(
index: _index,
children: [
GridView.builder(
itemCount: images.length,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onLongPress: () {
setState(() {
_index = 1;
_image = "assets/images/${images[index]}";
});
},
onLongPressEnd: (details) {
setState(() {
_index = 0;
});
},
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Card(
elevation: 4,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0),
),
clipBehavior: Clip.hardEdge,
child: Image.asset("assets/images/${images[index]}"),
),
),
);
},
),
Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.2),
),
child: Center(
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: 400,
maxWidth: 400,
),
child: Image.asset(
_image,
),
),
),
)
],
),
);
}
}
You can check output for above code here.
You could use Peek and Pop https://pub.dev/packages/peek_and_pop
Is an implementation for Flutter based on the iOS functionality of the same name.

Flutter - How to make a row to stay at the top of screen when scrolled

Iam trying to implement a appbar like this
When scrolling down I need to hide the search bar alone and pin the row and the tabs on the device top. Which is like
And when we scroll down the all the three rows needs to be displayed.
Using SliverAppBar with bottom property tabs are placed and pinned when scrolling, but a row above it should be pinned at the top above the tabbar. Im not able to add a column with the row and tabbar because of preferedSizeWidget in bottom property. Flexible space bar also hides with the appbar so I cannot use it. Does anyone know how to make this layout in flutter.
Please try this.
body: Container(
child: Column(
children: <Widget>[
Container(
// Here will be your AppBar/Any Widget.
),
Expanded(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
// All your scroll views
Container(),
Container(),
],
),
),
),
],
),
),
You could create your own SliverAppBar or you can divide them in 2 items, a SliverAppBar and a SliverPersistentHeader
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home>
with SingleTickerProviderStateMixin {
TabController controller;
TextEditingController textController = TextEditingController();
#override
void initState() {
super.initState();
controller = TabController(
length: 3,
vsync: this,
);
}
#override
void dispose(){
super.dispose();
controller.dispose();
textController.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
leading: const Icon(Icons.menu),
title: TextField(
controller: textController,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
isDense: true,
hintText: 'Search Bar',
hintStyle: TextStyle(color: Colors.black.withOpacity(.5), fontSize: 16),
border: InputBorder.none
)
),
snap: true,
floating: true,
actions: [
IconButton(
icon: const Icon(Icons.search),
onPressed: () => print('searching for: ${textController.text}'),
)
]
),
//This is Where you create the row and your tabBar
SliverPersistentHeader(
delegate: MyHeader(
top: Row(
children: [
for(int i = 0; i < 4; i++)
Expanded(
child: OutlineButton(
child: Text('button $i'),
onPressed: () => print('button $i pressed'),
)
)
]
),
bottom: TabBar(
indicatorColor: Colors.white,
tabs: [
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
Tab(text: 'Tab 3'),
],
controller: controller,
),
),
pinned: true,
),
SliverFillRemaining(
child: TabBarView(
controller: controller,
children: <Widget>[
Center(child: Text("Tab one")),
Center(child: Text("Tab two")),
Center(child: Text("Tab three")),
],
),
),
],
),
);
}
}
//Your class should extend SliverPersistentHeaderDelegate to use
class MyHeader extends SliverPersistentHeaderDelegate {
final TabBar bottom;
final Widget top;
MyHeader({this.bottom, this.top});
#override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
return Container(
color: Theme.of(context).accentColor,
height: math.max(minExtent, maxExtent - shrinkOffset),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if(top != null)
SizedBox(
height: kToolbarHeight,
child: top
),
if(bottom != null)
bottom
]
)
);
}
/*
kToolbarHeight = 56.0, you override the max and min extent with the height of a
normal toolBar plus the height of the tabBar.preferredSize
so you can fit your row and your tabBar, you give them the same value so it
shouldn't shrink when scrolling
*/
#override
double get maxExtent => kToolbarHeight + bottom.preferredSize.height;
#override
double get minExtent => kToolbarHeight + bottom.preferredSize.height;
#override
bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) => false;
}
UPDATE
A NestedScollView let you have 2 ScrollViews so you can control the inner scroll with the outer (just like you want with a TabBar)
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
TextEditingController textController = TextEditingController();
List<String> _tabs = ['Tab 1', 'Tab 2', 'Tab 3'];
// Your tabs, or you can ignore this and build your list
// on TabBar and the TabView like my previous example.
// I don't create a TabController now because I wrap the whole widget with a DefaultTabController
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
textController.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: DefaultTabController(
length: _tabs.length, // This is the number of tabs.
child: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled){
return <Widget>[
SliverOverlapAbsorber(
handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
sliver: SliverAppBar(
elevation: 0.0,
leading: const Icon(Icons.menu),
title: TextField(
controller: textController,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
isDense: true,
hintText: 'Search Bar',
hintStyle: TextStyle(
color: Colors.black.withOpacity(.5),
fontSize: 16),
border: InputBorder.none)
),
snap: true,
floating: true,
actions: [
IconButton(
icon: const Icon(Icons.search),
onPressed: () => print('searching for: ${textController.text}'),
)
]
),
),
SliverPersistentHeader(
delegate: MyHeader(
top: Row(children: [
for (int i = 0; i < 4; i++)
Expanded(
child: OutlineButton(
child: Text('button $i'),
onPressed: () => print('button $i pressed'),
))
]),
bottom: TabBar(
indicatorColor: Colors.white,
tabs: _tabs.map((String name) => Tab(text: name)).toList(),
),
),
pinned: true,
),
];
},
body: TabBarView(
children: _tabs.map((String name) {
return SafeArea(
child: Builder(
// This Builder is needed to provide a BuildContext that is
// "inside" the NestedScrollView, so that
// sliverOverlapAbsorberHandleFor() can find the
// NestedScrollView.
// You can ignore it if you're going to build your
// widgets in another Stateless/Stateful class.
builder: (BuildContext context) {
return CustomScrollView(
// The "controller" and "primary" members should be left
// unset, so that the NestedScrollView can control this
// inner scroll view.
// If the "controller" property is set, then this scroll
// view will not be associated with the NestedScrollView.
// The PageStorageKey should be unique to this ScrollView;
// it allows the list to remember its scroll position when
// the tab view is not on the screen.
key: PageStorageKey<String>(name),
slivers: <Widget>[
SliverOverlapInjector(
// This is the flip side of the SliverOverlapAbsorber
// above.
handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
),
SliverPadding(
padding: const EdgeInsets.all(8.0),
sliver: SliverFixedExtentList(
itemExtent: 48.0,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return ListTile(
title: Text('Item $index'),
onTap: () => print('$name at index $index'),
);
},
childCount: 30,
),
),
),
],
);
},
),
);
}).toList(),
),
),
));
}
}
import 'dart:io';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primaryColor: Colors.white,
),
home: NewsScreen(),
debugShowCheckedModeBanner: false,
);
}
}
class NewsScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() => _NewsScreenState();
}
class _NewsScreenState extends State<NewsScreen> {
final List<String> _tabs = <String>[
"Featured",
"Popular",
"Latest",
];
#override
Widget build(BuildContext context) {
return Material(
child: Scaffold(
body: DefaultTabController(
length: _tabs.length,
child: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
SliverOverlapAbsorber(
handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
sliver: SliverSafeArea(
top: false,
bottom: Platform.isIOS ? false : true,
sliver: SliverAppBar(
title: Text('Tab Demo'),
elevation: 0.0,
floating: true,
pinned: true,
snap: true,
forceElevated: innerBoxIsScrolled,
bottom: TabBar(
tabs: _tabs.map((String name) => Tab(text: name)).toList(),
),
),
),
),
];
},
body: TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
),
),
),
);
}
}

How to know when a list is long enough to be scrollable?

The screenshot below consists of two product listings, one which is too short to be scrollable, the other which is long enough to be scrollable.
Below is the screenshot with more visible colours for better clarity for the sake of this question:
To indicate to the user that the list is scrollable, I have stacked the list with a gradient which is at the end of the list.
I would like this gradient to only appear when the list is long enough to be scrollable, but I am not able to find a way to differentiate between the scrollable and non-scrollable lists.
Below is the code for the stack which has the underlying list and the gradient:
Stack(
children: <Widget>[
ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
//children go here
],
),
Align(
alignment: Alignment.centerRight,
child: Container(
width: 24,
height: 24,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: FractionalOffset.centerRight,
end: FractionalOffset.centerLeft,
colors: [
Colors.green,
Colors.yellow
],
stops: [
0.0,
1.0
]))),
),
],
),
I made a simple case for your request.
At first build list and calculate all item's widht sum,
and if all item's width is over Listview container's width, redraw show indicator that it can be scrollable.
modified
I changed to get a width dynamic ListView width.
You can just test with chaning 'listItemLength' value.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "App",
theme: new ThemeData(primarySwatch: Colors.amber),
home: Test(),
);
}
}
class Test extends StatefulWidget {
#override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
List<GlobalKey> _globalKeys = [];
GlobalKey _listviewGLobalKey = GlobalKey();
double listTotalWidth = 0.0;
double listviewWidth = 0.0;
int listItemLength = 14;
#override
void initState() {
super.initState();
for (var i = 0; i < listItemLength; i++) {
_globalKeys.add(GlobalKey());
}
WidgetsBinding.instance.addPostFrameCallback((_) => _getSizes());
}
_getSizes() {
// Get a total Items width
listTotalWidth = 0.0;
_globalKeys.forEach((key) {
final RenderBox renderBoxRed = key.currentContext.findRenderObject();
final containerSize = renderBoxRed.size;
listTotalWidth += containerSize.width;
});
print('total items width sum: $listTotalWidth');
// Get a ListView's width
final RenderBox listviewRenderBoxRed =
_listviewGLobalKey.currentContext.findRenderObject();
final listviewContainerSize = listviewRenderBoxRed.size;
listviewWidth = listviewContainerSize.width;
print('ListView width: $listviewWidth');
setState(() {});
}
#override
Widget build(BuildContext context) {
// print('**** ${_scrollController.position.maxScrollExtent}');
// WidgetsBinding.instance
// .addPostFrameCallback((_) => _getSizes());
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "Title",
theme: new ThemeData(primarySwatch: Colors.amber),
home: Scaffold(
body: SafeArea(
child: Container(
child: Row(
children: <Widget>[
Expanded(
child: ListView.builder(
key: _listviewGLobalKey,
scrollDirection: Axis.horizontal,
itemCount: listItemLength,
itemBuilder: (context, index) {
return Container(
key: _globalKeys[index],
padding: EdgeInsets.symmetric(horizontal: 5),
child: Center(
child: Text(
'aaa$index',
)));
},
),
),
if (listTotalWidth > listviewWidth) Icon(Icons.add),
],
),
),
),
),
);
}
}
attach a ScrollController to the ListView
and then use it (in a hack way) to determine scrollability of the list
ScrollController _scrollController = ScrollController();
return Container(
height: 24,
child: Stack(
children: <Widget>[
Container(
padding: EdgeInsets.only(right: 24),
child: ListView(
scrollDirection: Axis.horizontal,
controller: _scrollController,
children: <Widget>[
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
],
),
),
FutureBuilder(
future: Future.delayed(Duration(milliseconds: 500))
builder: (context,async){
if(async.connectionState == ConnectionState.waiting){
return Container();
}
return _scrollController.position.extentAfter > 0
? Align(
alignment: Alignment.centerRight,
child: Container(
width: 24,
height: 24,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: FractionalOffset.centerRight,
end: FractionalOffset.centerLeft,
colors: [Colors.green, Colors.yellow],
stops: [0.0, 1.0],
),
),
),
)
: Container();
},
),
],
),
);
This idea is from 'Muhammad Adam'.
When judge whether listview is scrollable, I used 'extentAfter' rather than 'renderBox size'.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
ScrollController _scrollController = ScrollController();
bool _scrollable = false;
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => _getIsScrollable());
}
_getIsScrollable() {
print(_scrollController.position.extentAfter > 0);
_scrollable = _scrollController.position.extentAfter > 0;
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: () {},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
Widget _buildBody() {
return Container(
height: 24,
child: Stack(
children: <Widget>[
Container(
padding: EdgeInsets.only(right: 24),
child: ListView(
scrollDirection: Axis.horizontal,
controller: _scrollController,
children: <Widget>[
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
Text('aaaindex'),
],
),
),
if (_scrollable)
Align(
alignment: Alignment.centerRight,
child: Container(
width: 24,
height: 24,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: FractionalOffset.centerRight,
end: FractionalOffset.centerLeft,
colors: [Colors.green, Colors.yellow],
stops: [0.0, 1.0],
),
),
),
),
],
),
);
}
}