— Flutter, Widgets — 1 min read
If you're working on a project that has API requests, chances are you might need to be able to reload lists with pull to refresh gestures. Doing this is really easy with Flutter's RefreshIndicator widget. Doing it on native Android is also, admittedly, relatively trivial but Flutter takes it another step further as always.
As for implementation, all you have to do is wrap your ListView with a RefreshIndicator widget. Here's an example(most of the unimportant logic is abbreviated):
1@override2 Widget build(BuildContext context) {3 return Scaffold(4 appBar: AppBar(5 ...6 ),7 body: Center(8 child: RefreshIndicator(9 child: ListView.builder(10 itemBuilder: (context, index) {11 ...12 },13 itemCount: _names.length,14 ),15 onRefresh: () async {16 ...17 },18 ),19 ),20 );21 }
As for the loading part, you just need to add your loading logic into the onRefresh
async method. After the user pulls down on the list it will automatically start the refreshing animation and the code in onRefresh
will be executed. Once onRefresh
has finished the loading animation will end by itself. It's all really handy because it seems to handle all of it's own state itself(this is what I feel makes it less verbose than the native Android equivalent). Here's a more thorough(but still simple) example of implementation:
1class _MyHomePageState extends State<MyHomePage> {2
3 List<String> _names = [];4
5 @override6 Widget build(BuildContext context) {7 return Scaffold(8 appBar: AppBar(9 title: Text(widget.title),10 ),11 body: Center(12 child: RefreshIndicator(13 child: ListView.builder(14 itemBuilder: (context, index) {15 final name = _names[index];16 return ListTile(17 title: Text(name),18 );19 },20 itemCount: _names.length,21 ),22 onRefresh: () async {23 setState(() {24 _names = ["Michael", "Chad", "Randy"];25 });26 },27 ),28 ),29 );30 }31}