我有7行,当我离开页面,再次进入同一页面,它显示14行



我有问题,当我运行代码,它的工作,但当我从页面出来,回去它显示x2的行,它的循环没有任何循环,我在我的数据库7行,当我出来,返回到同一页,它显示14行,但我只有7行。

这是我的代码:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class my_ads extends StatefulWidget {
const my_ads({Key? key}) : super(key: key);
@override
State<my_ads> createState() => _my_adsState();
}
List list = [];
int select_item = 0;
class _my_adsState extends State<my_ads> {
@override
Future MyAds() async {
final response =
await http.get(Uri.parse('https://***.***.***.**/getData.php'));
if (response.statusCode == 200) {
var red = jsonDecode(response.body);
setState(() {
list.addAll(red);
});
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load Ads');
}
}
@override
void initState() {
super.initState();
GetData();
}
GetData() async {
await MyAds();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Container(
margin: const EdgeInsets.only(left: 70, right: 60, top: 50),
height: 54.0,
width: 224.0,
child: Container(
decoration: BoxDecoration(
border:
Border.all(color: const Color(0xffF4AC47), width: 5),
color: const Color(0xff42A9D2),
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(40),
bottomRight: Radius.circular(40))),
child: const Center(
child: Text(
"MyAds",
style: TextStyle(
fontSize: 25,
color: Color(0xff072A52),
fontFamily: 'Cairo'),
textAlign: TextAlign.center,
),
//end logo
)),
),
const SizedBox(
height: 35,
),
Expanded(
child: ListView.builder(
itemCount: list.length,
itemBuilder: ((cts, i) {
return Column(
children: [
Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
height: 180.0,
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: const Color(0xff42A9D2), width: 5),
borderRadius: BorderRadius.circular(8)),
child: Row(
children: [
const Expanded(
flex: 3,
child: Image(
image: AssetImage("assets/book.jpg"),
),
),
Expanded(
flex: 6,
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"${list[i]["book_name"]}",
style: TextStyle(
fontSize: 20, color: Colors.black87),
),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text("${list[i]["collage"]}"),
const Icon(Icons.perm_identity_rounded)
],
),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text("${list[i]["loc"]}"),
const Icon(Icons.store)
],
),
],
),
)
],
),
),
),
const SizedBox(height: 16),
],
);
}),
),
),
],
),
);
}
}

我试图将此方法添加到我的PHP代码$mysqli_connect-> close();

但它不工作

这是我的PHP代码:
<?php
include("config.php");
$sql = "SELECT book_name,loc,com,spe,collage FROM ads";
$res = $connect->query($sql);
while($row = $res -> fetch_assoc()) {
$data[]=$row;
}
echo json_encode($data);
$mysqli_connect-> close();
?>

您在外部声明了列表。即使你换屏幕,它也会保持它的状态。要么在state小部件中声明它,要么替换为:

list.addAll(red);

由:

list = red;

最新更新