flutter - 如何使用颤振在 Listview rom API 上添加项目
问题描述
大家好,我正在使用颤振开发应用程序..所以我有列表视图,它正在显示来自 API URL 的数据,我工作得很好,我正在显示像卡片这样的数据,但是当它有一个新的时,我会在下面添加一张新卡片列表视图,但我需要在列表视图上方添加卡片我该怎么做?
这是我的代码
return FutureBuilder<List<Ravs>>(
future:hepler.fetchRav(),
builder:(context,snapshot) {
if (!snapshot.hasData) return Center(
child: CircularProgressIndicator(),
);
return Directionality(
textDirection: TextDirection.rtl,
child:Scaffold(
body:ListView(
children: snapshot.data
.map((data) =>
Card(
child: InkWell(
onTap:(){
Navigator.push(context, MaterialPageRoute (builder:(context)=>Showpage(id:data.id.toString()),
),
);
},
child: Column(
children: <Widget>[
new Container(
padding: const EdgeInsets.all(8.0),
alignment: Alignment.topLeft,
child: Image.network(data.image)
),
new Container(
padding: const EdgeInsets.all(10.0),
alignment: Alignment.topRight,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(data.nameravs,textDirection: TextDirection.rtl, style: Theme.of(context).textTheme.title),
Text(data.date_from,textAlign: TextAlign.right, style: TextStyle(color: Colors.black.withOpacity(0.5))),
Text(data.detalis , textAlign: TextAlign.right,),
],
)
)
],
),
),
)
)
.toList(),
)
)
);
},
);
我的 json 获取数据
Future<List<Ravs>> fetchRav() async {
String token = await read();
final String url= 'listravs';
String FullURL = Serveurl+url;
var response =await http.post(FullURL,
headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "Bearer $token"});
print('Token : ${token}');
print(response);
if (response.statusCode==200){
final items =jsonDecode(response.body).cast<Map<String,dynamic>>();
List<Ravs> listrav =items.map<Ravs>((json){
return Ravs.fromjson(json);
}).toList();
return listrav;
}
else{
throw Exception('Failed to load data from Server.');
}
}
类 Ravs
class Ravs {
int id;
String nameravs;
String date_from;
String detalis;
String image;
String date_to;
String time_from;
String time_to;
String address_ravs;
String pric_ravs;
String Captenname;
String Typeravs;
Ravs({
this.id,
this.nameravs,
this.date_from,
this.detalis,
this.image,
this.address_ravs,
this .Captenname,
this.date_to,
this.pric_ravs,
this.time_from,
this.time_to,
this.Typeravs,
});
factory Ravs.fromjson(Map<String ,dynamic>json ){
return Ravs(
id:json['id'],
nameravs:json['nameravs'],
date_from: json['date_from'],
detalis: json['detalis'],
image: json['image'],
date_to: json['date_to'],
address_ravs: json['address_ravs'],
pric_ravs: json['pric_ravs'],
time_from: json['time_from'],
time_to: json['time_to'] ,
Captenname: json['Captenname'],
Typeravs: json['Type_ravs'] ,
);
}
}
json
[
{
"id": 122,
"hall_name": "ahmed",
"image_path": "https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653002.jpg",
"hall_details": "The provided entry for `below` is not present in the Overlay",",
"hall_adress": "******"
},
{
"id": 132,
"hall_name": "Ali",
"image_path": "https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653181.png",
"hall_details": "The provided entry for `below` is not present in the Overlay",
"hall_adress": "********"
}, {
"id": 135,
"hall_name": "Ali",
"image_path": "https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653181.png",
"hall_details": "The provided entry for `below` is not present in the Overlay",
"hall_adress": "********"
}
]
解决方案
您可以在下面复制粘贴运行完整代码
我更改 json 字符串来模拟这种情况
您可以使用List.from
并addAll
创建新的List
ravsList = new List.from(ravsFromJson(response.body))..addAll(ravsList);
工作演示,你可以看到新List
的在旧的之上List
完整代码
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
// final ravs = ravsFromJson(jsonString);
import 'dart:convert';
List<Ravs> ravsFromJson(String str) =>
List<Ravs>.from(json.decode(str).map((x) => Ravs.fromJson(x)));
String ravsToJson(List<Ravs> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Ravs {
int id;
String hallName;
String imagePath;
String hallDetails;
String hallAdress;
Ravs({
this.id,
this.hallName,
this.imagePath,
this.hallDetails,
this.hallAdress,
});
factory Ravs.fromJson(Map<String, dynamic> json) => Ravs(
id: json["id"],
hallName: json["hall_name"],
imagePath: json["image_path"],
hallDetails: json["hall_details"],
hallAdress: json["hall_adress"],
);
Map<String, dynamic> toJson() => {
"id": id,
"hall_name": hallName,
"image_path": imagePath,
"hall_details": hallDetails,
"hall_adress": hallAdress,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
List<Ravs> ravsList = [];
String jsonString = '''
[
{
"id": 122,
"hall_name": "ahmed",
"image_path": "https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653002.jpg",
"hall_details": "The provided entry for `below` is not present in the Overlay",
"hall_adress": "******"
},
{
"id": 132,
"hall_name": "Ali",
"image_path": "https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653181.png",
"hall_details": "The provided entry for `below` is not present in the Overlay",
"hall_adress": "********"
}, {
"id": 135,
"hall_name": "Ali",
"image_path": "https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653181.png",
"hall_details": "The provided entry for `below` is not present in the Overlay",
"hall_adress": "********"
}
]
''';
void _incrementCounter() {
setState(() {
_counter++;
});
}
Future<List<Ravs>> fetchRav() async {
/*String token = await read();
final String url = 'listravs';
String FullURL = Serveurl + url;
var response = await http.post(FullURL, headers: {
HttpHeaders.contentTypeHeader: "application/json",
HttpHeaders.authorizationHeader: "Bearer $token"
});*/
http.Response response = http.Response(jsonString, 200);
//print('Token : ${token}');
//print(response);
if (response.statusCode == 200) {
/* final items = jsonDecode(response.body).cast<Map<String, dynamic>>();
List<Ravs> listrav = items.map<Ravs>((json) {
return Ravs.fromjson(json);
}).toList();*/
ravsList = new List.from(ravsFromJson(response.body))..addAll(ravsList);
return ravsList;
} else {
throw Exception('Failed to load data from Server.');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<Ravs>>(
future: fetchRav(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Center(
child: CircularProgressIndicator(),
);
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
body: ListView(
children: snapshot.data
.map((data) => Card(
child: InkWell(
onTap: () {
/*Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Showpage(id: data.id.toString()),
),
);*/
},
child: Column(
children: <Widget>[
new Container(
padding: const EdgeInsets.all(8.0),
alignment: Alignment.topLeft,
child: Image.network(data.imagePath)),
new Container(
padding: const EdgeInsets.all(10.0),
alignment: Alignment.topRight,
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(data.hallName,
textDirection: TextDirection.rtl,
style: Theme.of(context)
.textTheme
.title),
Text(data.hallAdress,
textAlign: TextAlign.right,
style: TextStyle(
color: Colors.black
.withOpacity(0.5))),
Text(
data.hallDetails,
textAlign: TextAlign.right,
),
],
))
],
),
),
))
.toList(),
)));
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Add your onPressed code here!
jsonString = '''
[
{
"id": 22,
"hall_name": "123",
"image_path": "https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653002.jpg",
"hall_details": "The provided entry for `below` is not present in the Overlay",
"hall_adress": "******"
},
{
"id": 32,
"hall_name": "456",
"image_path": "https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653181.png",
"hall_details": "The provided entry for `below` is not present in the Overlay",
"hall_adress": "********"
}, {
"id": 35,
"hall_name": "789",
"image_path": "https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653181.png",
"hall_details": "The provided entry for `below` is not present in the Overlay",
"hall_adress": "********"
}
]
''';
setState(() {});
},
child: Icon(Icons.navigation),
backgroundColor: Colors.green,
),
);
}
}
推荐阅读
- azure - 事件中心 API POST:40103:授权令牌签名无效
- c# - Roslyn 抛出不支持语言“VisualBasic”
- html - flex 容器中元素的宽度取决于最后一个元素中的内容
- c - 是否有可能:一个结构内的函数,它作用于同一结构的数据成员,而不必提供结构的自引用?
- jquery - 使用 Jquery 插件将 HTML 表格和表单数据导出到 Excel
- mobx-state-tree - 有动态类型支持吗?
- python - Python,用于 API 使用的 URI 中的正斜杠
- c++ - 类模板上一个特定函数的未解析外部符号
- angular - Angular 7 - 带有订阅的 observable 的单元测试
- c - 释放一部分 malloc