如何解决如何在带有提供程序的ListView中返回Future <double>?
我正在尝试使用Provider程序包将Future引入到列表视图中,但未成功。谁能给我一些建议或链接,以解释如何在返回双精度值的Future上实现notifylisteners()?
getPrice()的未来在这里:
beforeEach(async(() => {
Testbed.configureTestingModule({
imports: [RouterTestingModule,MatDialog,browserModule],declarations: [ DossierPersonalDataComponent ],providers: [{
provide: DomSanitizer,useValue: {
sanitize: () =>'safeString',bypassSecurityTrustHtml: () => 'safeString'
}
},DossierFileService,ErrorProcessor,]
})
.compileComponents();
}));
在这里,我试图将getPrice()的值输入到文本小部件中,但是却给了我“ Future的实例”而不是值。
import 'dart:collection';
import 'package:http/http.dart' as http;
import 'package:Flutter/material.dart';
import 'package:stock_watchlist/stock_service.dart';
class StockData extends ChangeNotifier {
List<Stock> _stocks = [
Stock(symbol: 'AAPL'),Stock(symbol: 'AMD'),Stock(symbol: 'TSLA')
];
UnmodifiableListView<Stock> get stocks {
return UnmodifiableListView(_stocks);
}
int get stockCount {
return _stocks.length;
}
void addStock(String symbol,double price,double eps) {
final stock = Stock(symbol: symbol);
_stocks.add(stock);
notifyListeners();
}
void deleteStock(Stock stock) {
_stocks.remove(stock);
notifyListeners();
}
Future<double> getPrice(String symbol) async {
String url =
"https://sandBox.iexapis.com/stable/stock/$symbol/quote/latestPrice?token=Tsk_38ddda0b877a4510b42a37ae713cdc96";
http.Response response = await http.get(url);
double price = double.tryParse(response.body);
return price;
}
Future<double> getEps(String symbol) async {
String url =
"https://sandBox.iexapis.com/stable/stock/$symbol/stats/ttmEPS?token=Tsk_38ddda0b877a4510b42a37ae713cdc96";
http.Response response = await http.get(url);
double eps = double.tryParse(response.body);
return eps;
}
}
解决方法
谢谢,我想我已经用FutureBuilder弄清楚了。这是我使用的代码。
class StockList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer<StockData>(
builder: (context,stockData,child) {
return ListView.builder(
itemCount: stockData.stockCount,itemBuilder: (context,index) {
//
final stockIndex = stockData.stocks[index];
//
return ListTile(
title: Text(
stockIndex.symbol,style: TextStyle(
color: kTextColor,),subtitle: FutureBuilder(
future: stockData.getPrice(stockIndex.symbol),builder: (context,snapshot) => Text(
snapshot.data.toString(),style: TextStyle(
color: kTextColor,);
},);
},);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。