提供程序Flutter-数据为null



我是flutter的新手,我在flutter和提供程序中做了一些错误的事情,因为当应用程序启动时,我没有提供程序数据。出了问题。你能帮帮我,告诉我我做错了什么吗?

这是我的代码

来自api 的响应

[{"id_imagen":"112","imagen":"20200608201951.jpg","texto":"I love you!!"}]  

service.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:miprincesa/model/image.dart';
import 'package:http/http.dart' as http;
class ImagesServices extends ChangeNotifier {
final String _url = "url api";
ImageList? datos;
bool isLoading = true;
ImagesServices() {
this.loadImage();
}
Future loadImage() async {
Map<String, String> headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Charset': 'utf-8'
};
final url = Uri.https(_url, "endPoint");
final resp = await http.get(url, headers: headers);
datos = ImageList.fromJson(jsonDecode(resp.body));
print("Imagen " + datos!.images[0].imagen);
notifyListeners();

}
}

我的模型图像.dart

class ImageList {
final List<Image> images;
ImageList({
required this.images,
});
factory ImageList.fromJson(List<dynamic> parsedJson) {
List<Image> data = [];
data = parsedJson.map((i) => Image.fromJson(i)).toList();
return new ImageList(images: data);
}
}
class Image {
String idImagen;
String imagen;
String texto;
Image({
required this.idImagen,
required this.imagen,
required this.texto,
});
factory Image.fromJson(Map<String, dynamic> json) {
return new Image(
idImagen: json['idImagen'].toString(),
imagen: json['imagen'],
texto: json['texto'],
);
}
}

和main.dart

import 'package:flutter/material.dart';
import 'dart:math';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:miprincesa/service/services.dart';
void main() => runApp(AppState());
class AppState extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [ChangeNotifierProvider(create: (_) => ImagesServices())],
child: MaterialApp(
title: 'Material App',
debugShowCheckedModeBanner: false,
home: SafeArea(child: _fondo()),
),
);
}
}
class _fondo extends StatelessWidget {
@override
Widget build(BuildContext context) {
var images = ['img.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png'];
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
"assets/" + images[Random().nextInt(images.length)]),
fit: BoxFit.fill),
),
child: Padding(
padding: const EdgeInsets.all(25.0),
child: Container(
decoration: _cardDecoration(),
child: Container(
child: _imagenCard(),
),
),
));
}
BoxDecoration _cardDecoration() => BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
boxShadow: [
BoxShadow(
color: Colors.black,
//Blur longitud, offset es la posicion
blurRadius: 15,
offset: Offset(0, 5))
],
);
}
class _imagenCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
MediaQueryData queryData;
queryData = MediaQuery.of(context);
final imageService = Provider.of<ImagesServices>(context);
print(imageService.datos!.images[0].imagen); // Error null value
return ConstrainedBox(
constraints:
BoxConstraints(minHeight: 150.0, maxHeight: queryData.size.height),
child: ClipRRect(
borderRadius: BorderRadius.circular(25.0),
child: Container(
alignment: Alignment.topCenter,
color: Colors.white,
child: Column(
children: [
FadeInImage(
placeholder: AssetImage('assets/jar-loading.gif'),
image:
NetworkImage('https://via.placeholder.com/400x600/f6f6f6'),
),
SizedBox(
height: 20,
),
Text("Texto de prueba",
style: GoogleFonts.dancingScript(
fontSize: 28, fontStyle: FontStyle.italic))
],
),
),
),
);
}
}

它通过空值给我一个异常,并且在y之后得到反数据

生成_imagenCard时引发了以下_CastError(脏,依赖项:[MediaQuery,_InheritedProviderScope<ImagesServices?>](:空值上使用的空检查运算符

I/flutter(7795(:Imagen 2020050609344.jpg

I/flutter(7795(:2020050609344.jpg

我做错了什么或做错了什么?

厚度

在访问数据之前,您的API调用似乎没有完成,这是一种奇怪的行为,因为您正在等待结果。您可以使用FutureBuilder小部件来等待API调用,并显示加载、完成和错误状态的特定小部件。

实现:将ConstrainedBox封装在FutureBuilder中。您可能需要在Provider.of<...>(context, //here)中添加参数listen: false,因为它将在notifyListeners之后进行侦听和重建。

相关内容

  • 没有找到相关文章

最新更新