我的水平ListView不滚动,我无法滑动。 ListView后面的项目可能有问题吗? 当我使背景透明时,我看到后面有一些错误。这可能是我无法刷卡的原因吗?
我从网站获取数据并将其直接加载到应用程序中,因此背面有很多卡。我在用3张图片实现加载功能之前进行了测试,效果很好。
cardscrollwidget.dart:
import 'dart:io';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'car.dart';
import 'main.dart';
class CardScrollWidget extends StatelessWidget {
var currentPage;
List<Car> allCars;
var padding = 20.0;
var verticalInset = 20.0;
CardScrollWidget(this.currentPage, this.allCars);
@override
Widget build(BuildContext context) {
return new AspectRatio(
aspectRatio: widgetAspectRatio,
child: LayoutBuilder(builder: (context, contraints) {
var width = contraints.maxWidth;
var height = contraints.maxHeight;
var safeWidth = width - 2 * padding;
var safeHeight = height - 2 * padding;
var heightOfPrimaryCard = safeHeight;
var widthOfPrimaryCard = heightOfPrimaryCard * cardAspectRatio;
var primaryCardLeft = safeWidth - widthOfPrimaryCard;
var horizontalInset = primaryCardLeft / 2;
List<Widget> cardList = new List();
for (var i = 0; i < allCars.length; i++) {
var delta = i - currentPage;
bool isOnRight = delta > 0;
String path = allCars[i].localImagePath;
var start = padding +
max(
primaryCardLeft -
horizontalInset * -delta * (isOnRight ? 15 : 1),
0.0);
const myColor = Color.fromRGBO(65, 106 , 128, 1);
var cardItem = Positioned.directional(
top: padding + verticalInset * max(-delta, 0.0),
bottom: padding + verticalInset * max(-delta, 0.0),
start: start,
textDirection: TextDirection.rtl,
child: ClipRRect(
borderRadius: BorderRadius.circular(16.0),
child: Container(
decoration: BoxDecoration(color: myColor, boxShadow: [
BoxShadow(
color: Colors.black12,
offset: Offset(3.0, 6.0),
blurRadius: 10.0)
]),
child: AspectRatio(
aspectRatio: cardAspectRatio,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Padding(padding: EdgeInsets.only(bottom: 160),
child: Image.file(File(path))), //220px × 165px ----------------- ERSTELLUNG AUTOCARD
Align(
alignment: Alignment.bottomLeft,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(
horizontal: 16.0, vertical: 8.0),
child: Text(allCars[i].model,
style: TextStyle(
color: Colors.black87,
fontSize: 25.0,
fontFamily: "SF-Pro-Text-Regular")),
),
SizedBox(
height: 10.0,
),
Padding(
padding: const EdgeInsets.only(
left: 12.0, bottom: 12.0),
child: Container(
padding: EdgeInsets.symmetric(
horizontal: 22.0, vertical: 6.0),
decoration: BoxDecoration(
color: Colors.blueAccent,
borderRadius: BorderRadius.circular(20.0)),
child: Text("Mehr Infos",
style: TextStyle(color: Colors.white)),
),
)
],
),
)
],
),
),
),
),
);
cardList.add(cardItem);
}
return Stack(
children: cardList,
);
}),
);
}
}
main.dart:
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'car.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'cardscrollwidget.dart';
import 'customIcons1.dart';
void main() => runApp(CarDealerApp());
//------------------- Variables
var cardAspectRatio = 12.0 / 16.0;
var widgetAspectRatio = cardAspectRatio * 1.2;
String carDataProvider = "DasWeltAuto";
String customerName = "lugmayr";
String customerId = "5386";
int carCount;
Map<String, bool> favouritedCars = new Map();
List<Car> completeCarList;
List<String> imagePaths = new List<String>();
//-----------------
// --------------------------------------------------- GEBRAUCHTWAGEN GET REQUEST UND FUTURES
Future<List<Car>> fetchAllCars() async {
completeCarList = new List();
var neededPages = 2; //2 nur moi für die loop, ned verwirren lossn von dem
for (var pageOfRequest = 1; pageOfRequest <= neededPages; pageOfRequest++) {
var response;
if (carDataProvider == 'DasWeltAuto') {
response = await http.get(
'https://www.dasweltauto.at/haendler/$customerName/$customerId/api/searchlist?btrnr=$customerId&page=$pageOfRequest');
}
if (response.statusCode == 200) {
var jsonBody = json.decode(response.body);
var growableList = jsonBody['list'];
for (var car in growableList) {
var preis = car['preis']['value'];
List<String> kampagnen = new List();
bool favourited = favouritedCars[car['index']] != null
? favouritedCars[car['index']]
: false;
String kredite = car['kredit'] != null
? car['kredit']['title2']
: "Kein Kreditangebot";
if (car['kampagnen'] != null) {
for (var kamp in car['kampagnen'])
kampagnen.add(kamp['title'].toString());
} else
kampagnen.add("Keine laufenden Kampagnen");
String listenPreis = car['listenPreisBrutto'] != null &&
car['listenPreisNetto'] != null
? "Brutto: ${car['listenPreisBrutto']['value']}, Netto: ${car['listenPreisNetto']['value']}"
: "Kein Listenpreis angeführt";
var carObject = new Car(
car['index'],
car['model'],
preis,
car['erstzulassung'],
car['erstzulassungsdatum'],
car['antrieb'],
car['getriebe'],
car['power'],
car['bildPath'],
kampagnen,
kredite,
listenPreis,
car['modelCode'],
car['marke'],
car['farbart'],
favourited);
await downloadImageForCar(carObject).then((path) {
carObject.localImagePath = path;
completeCarList.add(carObject);
})
// .catchError(handleDownloadError)
;
// completeCarList.add(carObject);
}
if (pageOfRequest == 1) {
carCount = jsonBody['count']['value'];
neededPages = determinePages(carCount, List.from(growableList));
}
} else {
throw Exception('Failed to load the car list');
}
}
return completeCarList;
}
String handleDownloadError(Exception ex) {
return "fuckkkk errrorrrrr ${ex.toString()}";
}
Future downloadImageForCar(Car carObject) async {
try {
var url = carObject.imageUrl + "/webp/420"; // <-- 1
var response = await get(url);
//.catchError(handleDownloadError); // <--2
var documentDirectory = await getApplicationDocumentsDirectory();
var firstPath = documentDirectory.path + "/carImages";
var filePathAndName =
documentDirectory.path + '/carImages/${carObject.localImageName()}.jpg';
await Directory(firstPath).create(recursive: true); // <-- 1
File imageFile = new File(filePathAndName); // <-- 2
imageFile.writeAsBytesSync(response.bodyBytes); // <-- 3
/* setState(() {
imageData = filePathAndName;
dataLoaded = true;
});
*/
imagePaths.add(filePathAndName);
return filePathAndName;
}
catch (e) {
print('Image download failed. details:\n $e');
}
}
int determinePages(int count, List carList) {
var listCount = carList.length;
double result = count / listCount;
return result.ceil();
}
//-------------------------------------------------------
//------------------------------------------------------------------------------------------ Layout and Widgets
/// This Widget is the main application widget.
class CarDealerApp extends StatelessWidget {
static const String _title = 'Car Dealer';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: CarDealerStatefulWidget(),
);
}
}
class CarDealerStatefulWidget extends StatefulWidget {
CarDealerStatefulWidget({Key key}) : super(key: key);
@override
_CarDealerStatefulWidgetState createState() =>
_CarDealerStatefulWidgetState();
}
class _CarDealerStatefulWidgetState extends State<CarDealerStatefulWidget> {
Future<List<Car>> _requestResult = fetchAllCars();
var currentPage;
Widget build(BuildContext context) {
PageController controller;
return DefaultTextStyle(
style: Theme.of(context).textTheme.headline2,
textAlign: TextAlign.center,
child: FutureBuilder<List<Car>>(
future: _requestResult, // a previously-obtained Future<String> or null
builder: (BuildContext context, AsyncSnapshot<List<Car>> snapshot) {
Widget child;
if (snapshot.hasData) {// ----------------------------------------------------------------------Data successfully loaded
currentPage = snapshot.data.length - 1;
controller = PageController(initialPage: snapshot.data.length - 1);
controller.addListener(() {
setState(() {
currentPage = controller.page;
});
});
child = Scaffold(
backgroundColor: Colors.transparent,
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
left: 12.0, right: 12.0, top: 30.0, bottom: 5.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(
CustomIcons.menu,
color: Colors.white,
size: 30.0,
),
onPressed: () {},
),
IconButton(
icon: Icon(
Icons.search,
color: Colors.white,
size: 30.0,
),
onPressed: () {},
)
],
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Ihre Fahrzeuge",
style: TextStyle(
color: Colors.white,
fontSize: 35.0,
fontFamily: "Calibre-Semibold",
letterSpacing: 1.0,
)),
IconButton(
icon: Icon(
CustomIcons.option,
size: 12.0,
color: Colors.white,
),
onPressed: () {},
)
],
),
),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Row(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Color(0xFFff6e6e),
borderRadius: BorderRadius.circular(20.0),
),
child: Center(),
),
SizedBox(
width: 15.0,
),
Text("${snapshot.data.length} Autos",
style: TextStyle(color: Colors.blueAccent))
],
),
),
Stack(
children: <Widget>[
CardScrollWidget(currentPage, snapshot.data), //------------------------------------- CARD SCROLL WIDGET CALL
Positioned.fill(
child: PageView.builder(
itemCount: snapshot.data.length,
controller: controller,
reverse: true,
itemBuilder: (context, index) {
return Container();
},
),
)
],
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Favouriten",
style: TextStyle(
color: Colors.white,
fontSize: 35,
fontFamily: "Calibre-Semibold",
letterSpacing: 1.0,
)),
IconButton(
icon: Icon(
CustomIcons.option,
size: 12.0,
color: Colors.white,
),
onPressed: () {},
)
],
),
),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Row(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.blueAccent,
borderRadius: BorderRadius.circular(20.0),
),
child: Center(
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 22.0, vertical: 6.0),
child: Text("Latest",
style: TextStyle(color: Colors.white)),
),
),
),
SizedBox(
width: 15.0,
),
Text("1 Auto", style: TextStyle(color: Colors.blueAccent))
],
),
),
SizedBox(
height: 20.0,
),
Row(
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 18.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: Image.asset("assets/image_02.jpg",
width: 296.0, height: 222.0),
),
)
],
)
],
),
),
);
}else if (snapshot.hasError) {
child = Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
);
} else {
child =
SizedBox(
child: CircularProgressIndicator(),
width: 60,
height: 60,
);
}
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF1b1e46),
Color(0xFF2d3447),
],
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
tileMode: TileMode.clamp)),
child: child
);
},
),
);
}
}