我想从_data
到main() async
访问Stateful Widget
吗?在Main()
中调用REST Api Call是一种好习惯吗?
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/material.dart';
Future main() async {
List _data = await makeRequest();
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
Future<List> makeRequest() async {
String url = "https://jsonplaceholder.typicode.com/posts";
http.Response response = await http.get(url);
print(json.decode(response.body));
return json.decode(response.body);
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("JSON List"),
),
body: ListView.builder(
itemBuilder: (BuildContext context, int index) {
ListTile(
);
}
),
);
}
}
答案 0 :(得分:4)
这就是它的工作方式,我已修复您的代码:
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List _data = new List();
void makeRequest() async {
String url = "https://jsonplaceholder.typicode.com/posts";
http.Response response = await http.get(url);
print(json.decode(response.body));
setState(() {
_data = json.decode(response.body) as List;
});
}
@override
void initState() {
makeRequest();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("JSON List"),
),
body: _data.isEmpty
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: _data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(_data[index]['title']),
);
}),
);
}
}
您的主要电话应该是
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}