Flutter-带有延迟请求的SearchDelegate中的FutureBuilder



我很难使用SearchDelegate实现简单的搜索功能。我想在用户停止键入后等待2秒钟,然后向API发出调用请求。

我已经检查了这个问题:如何在flutter的SearchPage Widget中取消搜索建议?并使用此程序包https://pub.dev/packages/debounce_throttle但仍然没有像我预期的那样工作。每当用户输入新字符时,应用程序就会立即发出呼叫请求。

这是buildResults函数的示例代码

@override
Widget buildResults(BuildContext context) {
return FutureBuilder(
builder: (BuildContext context, AsyncSnapshot<List<Place>> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return ListView.builder(
itemBuilder: (context, index) => ListTile(
leading: Icon(Icons.location_city),
title: Text(snapshot.data![index].name),
onTap: () { ... do something ... },
),
itemCount: snapshot.data!.length,
);
} else {
return Center(child: CircularProgressIndicator());
}
},
future: queryChanged(query),
);
}

和Future功能发出呼叫请求

Future<List<Place>> _getLocation() async {
List<Place> displayPlaces = [];
...
...
return displayPlaces;
}

Debuncert代码

final debouncer = Debouncer<String>(Duration(milliseconds: 2000), initialValue: '');
Future<List<Place>> queryChanged(String query) async {
debouncer.value = query;
return _getLocation();
}

此代码适用于我:

import 'package:debounce_throttle/debounce_throttle.dart';
import 'dart:async';
class AddressSearch extends SearchDelegate<Suggestion?> {

Completer<List<Suggestion>> _completer = Completer();
late final Debouncer _debouncer = Debouncer(Duration(milliseconds: 300),
initialValue: '',
onChanged: (value) {
_completer.complete(_fetchSuggestions(value)); // call the API endpoint
}
);
@override
Widget buildSuggestions(BuildContext context) {

_debouncer.value = query; // update the _debouncer
_completer = Completer(); // re-create the _completer, 'cause old one might be completed already 
return FutureBuilder<List<Suggestion>>(
future: _completer.future,
builder: (context, snapshot) {
/* render your suggestions here */
if (snapshot.connectionState == ConnectionState.done) {
// If we got an error
if (snapshot.hasError) {
return Center(
child: Text(
'${snapshot.error} occured',
style: TextStyle(fontSize: 18),
),
);
// if we got our data
} else if (snapshot.hasData) {
// Extracting data from snapshot object
return ListView.builder(
itemBuilder: (context, index) => ListTile(
title: Text((snapshot.data?[index])!.label), // or whatever field you have in your Suggestion class
onTap: () {
close(context, snapshot.data?[index]);
},
),
itemCount: snapshot.data?.length,
);
}
}
// Displaying LoadingSpinner to indicate waiting state
return Center(
child: CircularProgressIndicator(),
);
}
);
}
}

相关内容

  • 没有找到相关文章

最新更新