Flutter有状态代码问题.设置为setstate的内容是什么? [英] Flutter Stateful code problem. What to put in setstate?
问题描述
我从不久开始学习颤动.我非常了解编码,但是要理解有状态以及将哪些内容置于创建状态中,我还有一些问题.按照一个教程,我制作了这个应用程序,该应用程序加载了带有地震信息的json,并显示在带有滚动条的ListView中.现在,我想使其成为一个有状态的小部件,并通过onrefresh来更新json中的值.这是我的代码(无状态) `
I started learning flutter from a little while now. I quite understand the coding pretty much but I have still some problem to understand the Stateful and what to put in the create state. Following a tutorial I made this app that loads a json with earthquake info and displays in a ListView with a scrollbar on the side. Now I would love to make it a stateful widget and onrefresh to update the values from the json. Here is my code (Stateless) `
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
Map _quakes;
List _features; // oggesto list delle features
void main() async {
_quakes = await getQuakes();
_features = _quakes["features"];
runApp(new MaterialApp(
theme: new ThemeData(
accentColor: Colors.red,
),
debugShowCheckedModeBanner: false,
color: Colors.red,
title: "Terremoti",
home: new Quakes(),
));
}
class Quakes extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Tutti i Terremoti ultime 24h"),
centerTitle: true,
backgroundColor: Colors.red,
),
body: new Center(
child: new Scrollbar(
child: RefreshIndicator(
onRefresh: getQuakes,
child: ListView.builder(
itemCount: _features.length,
padding: const EdgeInsets.all(15.0),
itemBuilder: (BuildContext context, position) {
if (position.isOdd)
return new SizedBox(
height: 10.0,
child: new Center(
child: new Container(
margin: new EdgeInsetsDirectional.only(
start: 1.0, end: 1.0),
height: 2.5,
color: Colors.red,
),
),
);
final index = position ~/ 2;
var format = new DateFormat("dd MMM, yyyy, \n" + "HH:mm:ss");
//var dateString = format.format(format);
var date = format.format(
new DateTime.fromMillisecondsSinceEpoch(
_features[index]["properties"]["time"],
isUtc: true));
//creando le righe della listview
return new ListTile(
title: new Text(
"Magnitudo: ${_features[index]["properties"]["mag"]} \n $date",
style: new TextStyle(
fontSize: 21.0,
color: Colors.green,
fontWeight: FontWeight.w700),
),
subtitle: new Text(
"Luogo: ${_features[index]["properties"]["place"]}",
style: new TextStyle(
fontSize: 18.0,
),
),
);
}),
),
)),
);
}
}
Future<Map> getQuakes() async {
String apiUrl =
"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson";
http.Response response = await http.get(apiUrl);
return json.decode(response.body);
}
`
推荐答案
提取代码以重新加载列表,并使其成为State
类的实例方法.接下来,让列表为空(显示进度指示器).最后,从initState
调用reload方法.
Extract the code to reload the list, and make it an instance method of the State
class. Next, allow for the list to be empty (show a progress indicator). Finally, call the reload method from initState
.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
void main() async {
runApp(MaterialApp(
theme: ThemeData(
accentColor: Colors.red,
),
debugShowCheckedModeBanner: false,
color: Colors.red,
title: 'Terremoti',
home: Quakes(),
));
}
class Quakes extends StatefulWidget {
@override
State createState() => QuakesState();
}
class QuakesState extends State<Quakes> {
DateFormat format = DateFormat('dd MMM, yyyy, \nHH:mm:ss');
List _features;
@override
void initState() {
super.initState();
reload();
}
Future<void> reload() async {
final Map quakes = await getQuakes();
setState(() {
_features = quakes['features'];
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Tutti i Terremoti ultime 24h'),
centerTitle: true,
backgroundColor: Colors.red,
),
body: Center(
child: _features == null
? const CircularProgressIndicator()
: Scrollbar(
child: RefreshIndicator(
onRefresh: reload,
child: ListView.builder(
itemCount: _features.length,
padding: const EdgeInsets.all(15.0),
itemBuilder: (BuildContext context, position) {
if (position.isOdd)
return SizedBox(
height: 10.0,
child: Center(
child: Container(
margin: const EdgeInsetsDirectional.only(
start: 1.0,
end: 1.0,
),
height: 2.5,
color: Colors.red,
),
),
);
final int index = position ~/ 2;
final String date = format.format(
DateTime.fromMillisecondsSinceEpoch(
_features[index]['properties']['time'],
isUtc: true));
//creando le righe della listview
return ListTile(
title: Text(
"Magnitudo: ${_features[index]["properties"]["mag"]} \n $date",
style: const TextStyle(
fontSize: 21.0,
color: Colors.green,
fontWeight: FontWeight.w700),
),
subtitle: Text(
"Luogo: ${_features[index]["properties"]["place"]}",
style: const TextStyle(
fontSize: 18.0,
),
),
);
}),
),
),
),
);
}
}
Future<Map> getQuakes() async {
final http.Response response = await http.get(
'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson');
return json.decode(response.body);
}
这篇关于Flutter有状态代码问题.设置为setstate的内容是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!