我嘗試抓取網站以獲取一些資料(標題),然后將其存盤在字串串列中,以便稍后在我的文本小部件中使用,但問題是我的串列中沒有資料,為什么會這樣?當我在我的 dd 串列中使用 await 時,向我顯示錯誤,我需要讓我的 func 未來我嘗試在我的代碼中解釋更多請看這是我的代碼
// ignore: prefer_const_constructors
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:html/parser.dart';
import 'package:http/http.dart' as http;
import 'package:weatherapp/Test/datapars.dart';
class DataP extends StatelessWidget {
late List<String> dd = [];
Future<List<String>> arageek() async {
List<String> title = [];
var uri = Uri.parse('exmple.com');
var respons = await http.get(uri);
var doc = parse(respons.body);
final className =
doc.getElementsByClassName('WidePostCard_postTitle__SRltQ');
for (final data in className) {
title.add(data.text.toString());
print(data.text); // it show me all the title in my console
}
return title; // when i print this its show me list of my all title i get
}
@override
Widget build(BuildContext context) {
dd = await arageek(); // here result is emty and tell cant use await
print(dd);// show emty []
return Container(
alignment: Alignment.center,
child: Text(
'ddddddddddddd',
style: TextStyle(fontSize: 20),
),
);
}
}
uj5u.com熱心網友回復:
usingFutureBuilder可以解決您的問題,此入門代碼可能會幫助您:
class DataP extends StatelessWidget {
late List<String> dd = [];
Future<List<String>> arageek() async {
List<String> title = [];
var uri = Uri.parse('exmple.com');
var respons = await http.get(uri);
var doc = parse(respons.body);
final className =
doc.getElementsByClassName('WidePostCard_postTitle__SRltQ');
for (final data in className) {
title.add(data.text.toString());
print(data.text); // it show me all the title in my console
}
return title; // when i print this its show me list of my all title i get
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
// Initialize FlutterFire:
future: arageek(),
builder: (context, yourListOfStringResult) {
// Check for errors
if (yourListOfStringResult.hasError) {
return Text("something is wrong!");
} else if (yourListOfStringResult.connectionState == ConnectionState.done) {
List<String> data = yourListOfStringResult.data as List<String>; //
return Container(
alignment: Alignment.center,
child: Text(
'ddddddddddddd',
style: TextStyle(fontSize: 20),
),
);
}else return CircularProgressIndicator();
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449857.html
下一篇:回傳到顫振中查看
