Skip to content

Instantly share code, notes, and snippets.

@mjohnsullivan
Created July 8, 2020 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjohnsullivan/b552f03f013e88b8f9b9956a1224062b to your computer and use it in GitHub Desktop.
Save mjohnsullivan/b552f03f013e88b8f9b9956a1224062b to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() => runApp(KeepAliveExampleApp());
class KeepAliveExampleApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
body: KeepAlivePage(),
),
);
}
}
class KeepAlivePage extends StatefulWidget {
@override
_KeepAlivePageState createState() => _KeepAlivePageState();
}
class _KeepAlivePageState extends State<KeepAlivePage> {
var _offset = Offset.zero;
void _updateOffset(Offset offset) => setState(() => _offset = offset);
@override
Widget build(BuildContext context) {
return CustomScrollView(
slivers: [
SliverAppBar(
title: Text('Drag Position: $_offset'),
pinned: true,
),
SliverPadding(
padding: const EdgeInsets.only(top: 50),
),
SliverFixedExtentList(
itemExtent: 50,
delegate: SliverChildBuilderDelegate(
(itemContext, index) {
var keepAlive = index == 2;
return KeepAlive(
key: ValueKey<int>(index),
keepAlive: keepAlive,
child: KeepAliveListItem(index, _updateOffset),
);
},
findChildIndexCallback: (Key key) {
final valKey = key as ValueKey<int>;
return valKey.value;
},
addRepaintBoundaries: false,
addSemanticIndexes: false,
addAutomaticKeepAlives: false,
),
),
],
cacheExtent: 0,
);
}
}
class KeepAliveListItem extends StatelessWidget {
const KeepAliveListItem(this.index, this.updateOffset);
final int index;
final Function(Offset) updateOffset;
@override
Widget build(BuildContext context) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
child: Container(
height: 50,
width: 100,
color: Colors.lightBlue[100 * (index % 9)],
child: Center(
child: Text('Item $index ${index == 2 ? " (KEEPALIVE)" : ""}'),
),
),
onVerticalDragStart: (details) {},
onVerticalDragUpdate: (details) {
RenderBox getBox = context.findRenderObject() as RenderBox;
final local = getBox.globalToLocal(details.globalPosition);
updateOffset(local);
},
onVerticalDragEnd: (details) {},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment