我是Flutter的新手,请帮助。我正在尝试将json文件从url移动到资产文件夹,我无法考虑应该对代码进行哪些更改以使其起作用。
我试图修复它,但我不能,如果有人可以提供帮助,我会感激不尽。
这是我的代码:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'user.dart';
void main() {
runApp(new MaterialApp(home: HomePage()));
}
class HomePage extends StatefulWidget {
@override
HomePageState createState() => HomePageState();
}
List data;
List<User> userlist = List();
List<User> usersavedlist = List();
int index;
class HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'UserList Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('UserList Flutter'),
actions: <Widget>[
IconButton(icon: const Icon(Icons.list), onPressed: _pushSaved),
],
),
body: listView(),
),
);
}
Future<String> fetchData() async {
final url =
'https://raw.githubusercontent.com/highmobdevelopment/userlist/master/contacts.json';
final response = await http.get(url);
if (response.statusCode == 200) {
print('succesfull parse');
this.setState(() {
data = json.decode(response.body);
data.forEach((element) => userlist.add(new User.fromJson(element)));
});
}
return "Success!";
}
@override
void initState() {
super.initState();
fetchData();
}
listView() {
return ListView.builder(
itemCount: userlist == null ? 0 : userlist.length,
itemBuilder: (context, index) {
return Column(
children: <Widget>[_buildRow(index, userlist), const Divider()],
);
},
);
}
Widget _buildRow(index, userlist) {
final bool alreadySaved = usersavedlist.contains(userlist[index]);
return ListTile(
title: Text(
userlist[index].name
寻求支持,请解决此问题。
答案 0 :(得分:0)
您需要await fetchData()
,因为它返回了未来。您的initState()
可能看起来像这样:
@override
void initState() {
super.initState();
Future.microtask(() async {
await fetchData();
});
}