gpt4 book ai didi

listview - Flutter有状态代码问题。设置什么状态?

转载 作者:行者123 更新时间:2023-12-03 03:41:46 25 4
gpt4 key购买 nike

我从不久开始学习 flutter 。我非常了解编码,但是要了解有状态状态以及将哪些内容置于创建状态中,仍然有一些问题。按照一个教程,我制作了这个应用程序,该应用程序加载了带有地震信息的json,并显示在带有滚动条的ListView中。现在,我想使其成为一个有状态的小部件,并通过onrefresh来更新json中的值。这是我的代码(无状态)
`

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方法。

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);
}

关于listview - Flutter有状态代码问题。设置什么状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com