在 flutter 中列出来自 Json 的数据
List data from a Json in flutter
我正在尝试使用 ListView 显示 Json 的数据,但我无法占据第一个位置,因为它是一个自动生成的字符串,每条记录都会发生变化。
这是 Json 对我来说 API returns
{VOVQv28SU2c0GgXJKcSp8UFchPz2:
{email: bibiana206@gmail.com, fullname: bibiana, identification: e8104970, phone: 2095770, status: Waiting,
vehicle_details:
{car_brand: Ferrari, car_color: rojo, car_model: cretta, car_plate: az12}
},
dBncphEFOZbzGEt5qn44sD9BYVK2:
{email: bolivia20192019@gmail.com, fullname: Gustavo Barrios, identification: 14326048, phone: 60697350, status: Active,
vehicle_details:
{car_brand: Renault, car_color: Gris, car_model: Duster, car_plate: AY6787,}
}
}
您可以将 JSON 转换为 List,如下所示:
Map<String, dynamic> json = {};
// Here you only take the values of the JSON (you ignore it's keys)
List values = json.values.toList();
// Now you can access the values of the JSON using List functions
values[0]
values.first
...
如果您需要 JSON 的密钥,那么您可以这样做:
List<MapEntry> entries = json.entries.toList();
// Now you can access it's entries as a list like so
entries[0].key
entries[0].value
entries.first.key
entries.first.value
希望这能解决您的问题。如果没有,请告诉我
要使用ListView
中的数据
ListView.builder(
itemCount: values.length,
builder: (context, index) {
final value = values[index];
return ListTile(
title: Text(value['fullname']),
subtitle: Text("${value['identification']}"),
);
}
);
我还建议,首先将 JSON 数据转换为数据对象。这使得实施更加直接并且是常见的做法。
看看JSON序列化:https://flutter.dev/docs/development/data-and-backend/json
还没有我无法获取数据来显示这就是我正在编程的内容
Future<Widget> driverItem() async {
DatabaseSnapshot snapshot = await driverRef.once();
Map<String, dynamic> json = snapshot.value;
List values = json.values.toList();
if (values.length != 0) {
return ListView.builder(
itemCount: values.length,
itemBuilder: (context, index) {
final value = values[index];
return ListTile(
title: Text(value['fullname']),
subtitle: Text(value['email']),
);
},
);
}
}
当我 运行 网络时 returns 对我来说
DevTools failed to load SourceMap: Could not load content for https://www.gstatic.com/firebasejs/8.1.1/firebase-app.js.map: Load canceled due to load timeout
DevTools failed to load SourceMap: Could not load content for https://www.gstatic.com/firebasejs/7.23.0/firebase-database.js.map: Load canceled due to load timeout
DevTools failed to load SourceMap: Could not load content for https://www.gstatic.com/firebasejs/7.23.0/firebase-auth.js.map: Load canceled due to load timeout
DevTools failed to load SourceMap: Could not load content for https://www.gstatic.com/firebasejs/8.1.1/firebase-analytics.js.map: Load canceled due to load timeout
js_primitives.dart:47 NoSuchMethodError: method not found: 'bZ' (a.bZ is not a function)
js_primitives.dart:47 at qh.Bi (http://localhost:59423/main.dart.js:54609:15)
js_primitives.dart:47 at qh.d6 (http://localhost:59423/main.dart.js:54568:16)
js_primitives.dart:47 at qh.eS (http://localhost:59423/main.dart.js:54920:8)
js_primitives.dart:47 at qh.Bi (http://localhost:59423/main.dart.js:54610:3)
js_primitives.dart:47 at qh.d6 (http://localhost:59423/main.dart.js:54568:16)
js_primitives.dart:47 at qh.eS (http://localhost:59423/main.dart.js:54920:8)
js_primitives.dart:47 at qh.Bi (http://localhost:59423/main.dart.js:54610:3)
js_primitives.dart:47 at qh.d6 (http://localhost:59423/main.dart.js:54568:16)
js_primitives.dart:47 at qh.eS (http://localhost:59423/main.dart.js:54920:8)
js_primitives.dart:47 at wT.Bi (http://localhost:59423/main.dart.js:54610:3)
这是页面上的所有代码
class DriverPages extends StatefulWidget {
static final routeName = 'DriverPage';
DriverPages({Key key}) : super(key: key);
@override
_DriverPagesState createState() => _DriverPagesState();
}
DatabaseRef driverRef =
FirebaseDatabaseWeb.instance.reference().child('drivers');
class _DriverPagesState extends State<DriverPages> {
GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
List<Driver> items;
Future<Widget> driverItem() async {
DatabaseSnapshot snapshot = await driverRef.once();
Map<String, dynamic> json = snapshot.value;
List values = json.values.toList();
if (values.length != 0) {
return ListView.builder(
itemCount: values.length,
itemBuilder: (context, index) {
final value = values[index];
return ListTile(
title: Text(value['fullname']),
subtitle: Text(value['email']),
);
},
);
}
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
if (userSnapshot != null) {
return Scaffold(
key: scaffoldKey,
drawer: Container(
width: 320,
color: Colors.white,
child: Drawer(
child: PatimovilMenu(),
),
),
body: Container(
width: double.infinity,
height: double.infinity,
padding: EdgeInsets.symmetric(
vertical: 25,
horizontal: 30,
),
child: Column(
children: <Widget>[
PatimovilHeader(
onPressed: () {
scaffoldKey.currentState.openDrawer();
},
titlePage: 'Administrador de Conductores',
),
Container(
width: MediaQuery.of(context).size.width,
height: (MediaQuery.of(context).size.height) - 260,
alignment: Alignment.center,
child: Center(
child: driverItem() ?? Text('Nothing Drivers'),
),
),
PatimovilFooder(),
],
),
),
);
} else {
Navigator.pushNamedAndRemoveUntil(
context,
LoginPage.routeName,
(route) => false,
);
}
}
}
我附上 HTML 代码
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
Fore more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
-->
<base href="/">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="patimovil_admin">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>patimovil_admin</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://api.daytonsquareroots.org/firebasedatabaseweb/v0.0.2/app.js" defer></script>
<script src="https://www.gstatic.com/firebasejs/7.23.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.23.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-analytics.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script src="main.dart.js" type="application/javascript"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: FIREBASE_API_KEY,
authDomain: "patimovil-ccb6a.firebaseapp.com",
databaseURL: "https://patimovil-ccb6a.firebaseio.com",
projectId: "patimovil-ccb6a",
storageBucket: "patimovil-ccb6a.appspot.com",
messagingSenderId: "25248889320",
appId: "1:25248889320:web:b21fd8ea8fefcaadb78c5d",
measurementId: "G-Z4D23GMTK9"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('flutter-first-frame', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
非常感谢您的合作并指出我所犯的错误,我附上了您所要求的文件。
name: patimovil_admin
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: "none" # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.1
firebase_auth: ^0.18.4
firebase_core: ^0.5.3
firebase_db_web_unofficial: ^0.0.2
google_maps_flutter: ^1.0.6
google_maps_flutter_web: ^0.1.0+8
toast: ^0.1.5
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- images/
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
我正在尝试使用 ListView 显示 Json 的数据,但我无法占据第一个位置,因为它是一个自动生成的字符串,每条记录都会发生变化。
这是 Json 对我来说 API returns
{VOVQv28SU2c0GgXJKcSp8UFchPz2:
{email: bibiana206@gmail.com, fullname: bibiana, identification: e8104970, phone: 2095770, status: Waiting,
vehicle_details:
{car_brand: Ferrari, car_color: rojo, car_model: cretta, car_plate: az12}
},
dBncphEFOZbzGEt5qn44sD9BYVK2:
{email: bolivia20192019@gmail.com, fullname: Gustavo Barrios, identification: 14326048, phone: 60697350, status: Active,
vehicle_details:
{car_brand: Renault, car_color: Gris, car_model: Duster, car_plate: AY6787,}
}
}
您可以将 JSON 转换为 List,如下所示:
Map<String, dynamic> json = {};
// Here you only take the values of the JSON (you ignore it's keys)
List values = json.values.toList();
// Now you can access the values of the JSON using List functions
values[0]
values.first
...
如果您需要 JSON 的密钥,那么您可以这样做:
List<MapEntry> entries = json.entries.toList();
// Now you can access it's entries as a list like so
entries[0].key
entries[0].value
entries.first.key
entries.first.value
希望这能解决您的问题。如果没有,请告诉我
要使用ListView
ListView.builder(
itemCount: values.length,
builder: (context, index) {
final value = values[index];
return ListTile(
title: Text(value['fullname']),
subtitle: Text("${value['identification']}"),
);
}
);
我还建议,首先将 JSON 数据转换为数据对象。这使得实施更加直接并且是常见的做法。
看看JSON序列化:https://flutter.dev/docs/development/data-and-backend/json
还没有我无法获取数据来显示这就是我正在编程的内容
Future<Widget> driverItem() async {
DatabaseSnapshot snapshot = await driverRef.once();
Map<String, dynamic> json = snapshot.value;
List values = json.values.toList();
if (values.length != 0) {
return ListView.builder(
itemCount: values.length,
itemBuilder: (context, index) {
final value = values[index];
return ListTile(
title: Text(value['fullname']),
subtitle: Text(value['email']),
);
},
);
}
}
当我 运行 网络时 returns 对我来说
DevTools failed to load SourceMap: Could not load content for https://www.gstatic.com/firebasejs/8.1.1/firebase-app.js.map: Load canceled due to load timeout
DevTools failed to load SourceMap: Could not load content for https://www.gstatic.com/firebasejs/7.23.0/firebase-database.js.map: Load canceled due to load timeout
DevTools failed to load SourceMap: Could not load content for https://www.gstatic.com/firebasejs/7.23.0/firebase-auth.js.map: Load canceled due to load timeout
DevTools failed to load SourceMap: Could not load content for https://www.gstatic.com/firebasejs/8.1.1/firebase-analytics.js.map: Load canceled due to load timeout
js_primitives.dart:47 NoSuchMethodError: method not found: 'bZ' (a.bZ is not a function)
js_primitives.dart:47 at qh.Bi (http://localhost:59423/main.dart.js:54609:15)
js_primitives.dart:47 at qh.d6 (http://localhost:59423/main.dart.js:54568:16)
js_primitives.dart:47 at qh.eS (http://localhost:59423/main.dart.js:54920:8)
js_primitives.dart:47 at qh.Bi (http://localhost:59423/main.dart.js:54610:3)
js_primitives.dart:47 at qh.d6 (http://localhost:59423/main.dart.js:54568:16)
js_primitives.dart:47 at qh.eS (http://localhost:59423/main.dart.js:54920:8)
js_primitives.dart:47 at qh.Bi (http://localhost:59423/main.dart.js:54610:3)
js_primitives.dart:47 at qh.d6 (http://localhost:59423/main.dart.js:54568:16)
js_primitives.dart:47 at qh.eS (http://localhost:59423/main.dart.js:54920:8)
js_primitives.dart:47 at wT.Bi (http://localhost:59423/main.dart.js:54610:3)
这是页面上的所有代码
class DriverPages extends StatefulWidget {
static final routeName = 'DriverPage';
DriverPages({Key key}) : super(key: key);
@override
_DriverPagesState createState() => _DriverPagesState();
}
DatabaseRef driverRef =
FirebaseDatabaseWeb.instance.reference().child('drivers');
class _DriverPagesState extends State<DriverPages> {
GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
List<Driver> items;
Future<Widget> driverItem() async {
DatabaseSnapshot snapshot = await driverRef.once();
Map<String, dynamic> json = snapshot.value;
List values = json.values.toList();
if (values.length != 0) {
return ListView.builder(
itemCount: values.length,
itemBuilder: (context, index) {
final value = values[index];
return ListTile(
title: Text(value['fullname']),
subtitle: Text(value['email']),
);
},
);
}
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
if (userSnapshot != null) {
return Scaffold(
key: scaffoldKey,
drawer: Container(
width: 320,
color: Colors.white,
child: Drawer(
child: PatimovilMenu(),
),
),
body: Container(
width: double.infinity,
height: double.infinity,
padding: EdgeInsets.symmetric(
vertical: 25,
horizontal: 30,
),
child: Column(
children: <Widget>[
PatimovilHeader(
onPressed: () {
scaffoldKey.currentState.openDrawer();
},
titlePage: 'Administrador de Conductores',
),
Container(
width: MediaQuery.of(context).size.width,
height: (MediaQuery.of(context).size.height) - 260,
alignment: Alignment.center,
child: Center(
child: driverItem() ?? Text('Nothing Drivers'),
),
),
PatimovilFooder(),
],
),
),
);
} else {
Navigator.pushNamedAndRemoveUntil(
context,
LoginPage.routeName,
(route) => false,
);
}
}
}
我附上 HTML 代码
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
Fore more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
-->
<base href="/">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="patimovil_admin">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>patimovil_admin</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://api.daytonsquareroots.org/firebasedatabaseweb/v0.0.2/app.js" defer></script>
<script src="https://www.gstatic.com/firebasejs/7.23.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.23.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-analytics.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script>
<script src="main.dart.js" type="application/javascript"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: FIREBASE_API_KEY,
authDomain: "patimovil-ccb6a.firebaseapp.com",
databaseURL: "https://patimovil-ccb6a.firebaseio.com",
projectId: "patimovil-ccb6a",
storageBucket: "patimovil-ccb6a.appspot.com",
messagingSenderId: "25248889320",
appId: "1:25248889320:web:b21fd8ea8fefcaadb78c5d",
measurementId: "G-Z4D23GMTK9"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('flutter-first-frame', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
非常感谢您的合作并指出我所犯的错误,我附上了您所要求的文件。
name: patimovil_admin
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: "none" # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.1
firebase_auth: ^0.18.4
firebase_core: ^0.5.3
firebase_db_web_unofficial: ^0.0.2
google_maps_flutter: ^1.0.6
google_maps_flutter_web: ^0.1.0+8
toast: ^0.1.5
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- images/
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages