Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 如何使用flatter在up-on-Listview-romapi中添加项_Flutter - Fatal编程技术网

Flutter 如何使用flatter在up-on-Listview-romapi中添加项

Flutter 如何使用flatter在up-on-Listview-romapi中添加项,flutter,Flutter,大家好,我正在使用flatter开发应用程序。所以我有列表视图,它显示来自API URL的数据 工作正常,我显示的数据类似于卡片,但当它有一个新卡片时,我会在列表视图下添加一个新卡片,但我需要在列表视图上添加卡片,我如何才能做到这一点?? 这是我的代码 return FutureBuilder<List<Ravs>>( future:hepler.fetchRav(), builder:(context,snapshot) { if (!snapshot

大家好,我正在使用flatter开发应用程序。所以我有列表视图,它显示来自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(),
            )

        )
    );
  },
);
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.');
    }

  }
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'] ,

    );

  }


}
[  
    {
        "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);
在演示中,您可以看到新的
列表
位于旧的
列表

ravsList = new List.from(ravsFromJson(response.body))..addAll(ravsList);

完整代码

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,
      ),
    );
  }
}
导入“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
//要解析此JSON数据,请执行以下操作
//
//最终ravs=ravsFromJson(jsonString);
导入“dart:convert”;
列表ravsFromJson(字符串str)=>
List.from(json.decode(str.map)(x)=>Ravs.fromJson(x));
字符串ravsToJson(列表数据)=>
encode(List.from(data.map((x)=>x.toJson());
Ravs级{
int-id;
字符串名;
字符串图像路径;
字符串详细信息;
弦乐;
Ravs({
这个身份证,
这是我的名字,
这个.imagePath,
这是一个细节,
这是哈莱迪斯,
});
工厂Ravs.fromJson(映射json)=>Ravs(
id:json[“id”],
hallName:json[“hall_name”],
imagePath:json[“图像路径”],
hallDetails:json[“hall_details”],
hallAdress:json[“hall_address”],
);
映射到JSON()=>{
“id”:id,
“霍尔名称”:霍尔名称,
“图像路径”:图像路径,
“大厅详细信息”:大厅详细信息,
“霍尔地址”:霍尔地址,
};
}
void main(){
runApp(MyApp());
}
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“颤振演示”,
主题:主题数据(
主样本:颜色。蓝色,
),
主页:MyHomePage(标题:“颤振演示主页”),
);
}
}
类MyHomePage扩展StatefulWidget{
MyHomePage({Key,this.title}):超级(Key:Key);
最后的字符串标题;
@凌驾
_MyHomePageState createState()=>\u MyHomePageState();
}
类_MyHomePageState扩展状态{
int _计数器=0;
列表ravsList=[];
字符串jsonString='''
[  
{
“id”:122,
“大厅名称”:“艾哈迈德”,
“图像路径”:https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653002.jpg",
“大厅详细信息”:“覆盖图中不存在为`below`提供的条目”,
“大厅地址”:“******”
},
{
“id”:132,
“大厅名称”:“阿里”,
“图像路径”:https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653181.png",
“大厅详细信息”:“覆盖图中不存在为`below`提供的条目”,
“大厅地址”:“********”
}, {
“id”:135,
“大厅名称”:“阿里”,
“图像路径”:https://fathomless-brushlands-95996.herokuapp.com/Imaga_halls/1584653181.png",
“大厅详细信息”:“覆盖图中不存在为`below`提供的条目”,
“大厅地址”:“********”
}
]
''';
void _incrementCounter(){
设置状态(){
_计数器++;
});
}
未来的fetchRav()异步{
/*字符串标记=等待读取();
最终字符串url='listravs';
字符串FullURL=Serveurl+url;
var response=wait http.post(完整URL,标题:{
HttpHeaders.contentTypeHeader:“应用程序/json”,
HttpHeaders.authorizationHeader:“持票人$token”
});*/
http.Response=http.Response(jsonString,200);
//打印('Token:${Token}');
//打印(回复);
如果(response.statusCode==200){
/*final items=jsonDecode(response.body.cast();
List listrav=items.map((json){
返回Ravs.fromjson(json);
}).toList()*/
ravsList=newlist.from(ravsFromJson(response.body))…addAll(ravsList);
返回ravsList;
}否则{
抛出异常('未能从服务器加载数据');
}
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
正文:未来建设者(
future:fetchRav(),
生成器:(上下文,快照){
如果(!snapshot.hasData)
返回中心(
子对象:CircularProgressIndicator(),
);
返回方向性(
textDirection:textDirection.rtl,
孩子:脚手架(
正文:ListView(
子项:snapshot.data
.map((数据)=>卡(
孩子:InkWell(
onTap:(){
/*导航器。推(
上下文
材料路线(
生成器:(上下文)=>
Showpage(id:data.id.toString()),
),
);*/
},
子:列(
儿童:[
新容器(
填充:常数边集全部(8.0),
对齐:alignment.topLeft,
子项:Image.network(data.imagePath)),
新容器(
填充:常数边集全部(10.0),
对齐:alignment.topRight,
子:列(
主轴对准:
MainAxisAlignment.space,
横轴对齐:
CrossAxisAlignment.start,
儿童:[
文本(da)