扑灭错误 :必须为文本窗口小部件提供非空字符串。 'package:flutter / src / widgets / text.dart':断言失败:第360行pos 10:'data!= null'
引发了另一个异常:必须向Text小部件提供非null的字符串。
这是 Main.dart
import 'package:bheekho_foundation/widgets/app.dart';
import 'package:flutter/material.dart';
void main() {
runApp(App());
}
这是 App.dart
import 'package:bheekho_foundation/screens/home.dart';
import 'package:flutter/material.dart';
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
这是 Home.dart
import 'dart:convert';
import 'package:bheekho_foundation/models/request.dart';
import 'package:bheekho_foundation/services/request_service.dart';
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
RequestService _requestService = RequestService();
// ignore: unused_element
Future<List<Request>> _getAllRequest() async {
var result = await _requestService.getAllRequests();
List<Request> _list = List<Request>();
if (result != null) {
var requests = json.decode(result.body);
requests.forEach((request) {
var model = Request();
model.user_id = request['user_id'];
model.concern = request['concern'];
model.message = request['message'];
setState(() {
_list.add(model);
});
});
}
return _list;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Bheekho App"),
),
body: FutureBuilder<List<Request>>(
future: _getAllRequest(),
builder:
(BuildContext context, AsyncSnapshot<List<Request>> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Column(
children: [
Card(
child: Text(snapshot.data[index].user_id),
),
],
);
});
} else {
return Container(
child: Text('loading...'),
);
}
},
));
}
}
这是我的模型 request.dart
class Request {
// ignore: non_constant_identifier_names
int request_id;
// ignore: non_constant_identifier_names
String user_id;
String concern;
String message;
}
这是 Request_Service.dart
import 'package:bheekho_foundation/repository/repository.dart';
class RequestService {
Repository _repository;
RequestService() {
_repository = Repository();
}
getAllRequests() async {
return await _repository.httpGet('users');
}
}
这是 Repository.dart
import 'package:http/http.dart' as http;
class Repository {
String _baseUrl = "http://localhost:8000/api";
httpGet(String api) async {
return await http.get(_baseUrl + "/" + api);
}
}
答案 0 :(得分:1)
此时您的snapshot.data [index] .user_id最有可能为null。 为确保不为Text小部件分配空值,可以将其更改为以下内容:
Text(
snapshot.data[index].user_id != null
? snapshot.data[index].user_id
: ""
)
这实际上检查数据是否为null,否则检查快照数据。如果是这样,它将加载一个空字符串。