Есть ли лучший способ асинхронной загрузки данных в CupertinoPicker?

#flutter #cupertinopicker

#flutter #cupertinopicker

Вопрос:

Есть ли лучший способ асинхронной загрузки данных по требованию в CupertinoPicker?

Что я в основном делаю, так это прослушиваю событие прокрутки и определяю, прокручивается ли CupertinoPicker после начала, и показываю счетчик на время загрузки «данных». Я вставляю счетчик в список виджетов, созданных на основе данных, и удаляю его, когда в список добавляются новые виджеты.

Я не могу сказать, что заставляет меня задуматься, есть ли лучший способ, но я чувствую, что должен быть лучший способ решения этой проблемы.

 import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Widget> items = [Divider(color: Colors.red)];
  bool refreshInProgress = false;

  loadMoreData() {
    if(refreshInProgress) return;

    setState(() {
      refreshInProgress = true;
    });

    items.insert(0, FutureBuilder(
      future: Future.delayed(Duration(seconds: 2)).then((value) {
        var newItems = [Text("A"), Text("B"), Text("C")];

        setState((){
          items = [...newItems, ...items.where((w) => !(w is FutureBuilder) || w == null)];
          refreshInProgress = false;
        });

        return newItems;
      }),
      builder: (context, snapshot) {
        if(snapshot.connectionState == ConnectionState.waiting) return Center(child: CircularProgressIndicator());

        return null;
      },        
    ));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(child: Container(
          margin: EdgeInsets.all(20),
          child: Column(children: [
            Expanded(flex: 4, child: NotificationListener<ScrollNotification>(
              onNotification: (ScrollNotification notification) {
                if ((notification is ScrollEndNotification) amp;amp; notification.metrics.pixels <= 0) {
                  loadMoreData();
                  return true;
                }
                
                return false;
              },
              child: CupertinoPicker.builder(
                itemExtent: 32,
                itemBuilder: (BuildContext context, int index) {
                  if(index >= 0 amp;amp; index < items.length) return Center(child: items[index]);

                  return null;
                },
                onSelectedItemChanged: (int value) { 
                  print("onSelectedItemChanged: $value");
                },              
              ))
            ),
            Expanded(child: Container(child: Text("$items"))),
            Row(children: [
              RaisedButton(onPressed: () => setState(() => loadMoreData()), child: Text("Load more data")),
            ])
          ],
        )),
      )),
    );
  }
}
  

https://dartpad.dev/b27137f4bff39281980f5957f5e140ad