import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:http/http.dart' as http;
import 'package:html/parser.dart' as parser;
import 'package:html/dom.dart' as dom;
import 'package:plant_app/constants.dart';
import 'package:url_launcher/url_launcher.dart';
class Post extends StatefulWidget {
@override
_PostState createState() => _PostState();
}
class _PostState extends State<Post> {
List<String> post = List();
void _getDataFromWeb() async {
String str = "http://yongwon-h.gne.go.kr/yongwon-h/main.do#";
Uri uri = Uri.parse(str);
final response = await http.get(uri);
dom.Document document = parser.parse(response.body);
final elements = document.getElementsByClassName('meal_list');
setState(() {
post = elements
.map((element) => element.getElementsByTagName("p")[0].innerHtml)
.toList();
});
}
@override
// ignore: must_call_super
void initState() {
_getDataFromWeb();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: kPrimaryColor,
body: post.length == 0
? Text("No data", style: TextStyle(color: Colors.white))
: ListView.builder(
itemCount: post.length,
itemBuilder: (context, index) {
return AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 375),
child: SlideAnimation(
child: FadeInAnimation(
child: GestureDetector(
onTap: () async {
dynamic url = post[index];
if (await canLaunch(url))
launch(url);
else {
print('error');
}
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Container(
child: Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Text(
post[index],
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red,
fontSize: 20,
),
),
),
],
),
),
),
),
),
)),
);
}),
);
}
}
<块引用>
[RangeError(RangeError (index): Invalid value: Valid value range is empty: 0)]
有什么问题吗? 看完this YouTube video后我正在应用它。
我认为 0 是问题所在。
答案 0 :(得分:0)
根据 API 的响应,.meal_list 类被分配给一个段落标签。因此,在通过地图应用任何转换之前,您需要检查 elements
的值。
final elements = document.getElementsByClassName('meal_list')
返回一个单项的 Node 列表,你可以像这样访问它的内容 elements[0].innerText
。