我想将数据从模型数据发送到另一页。实际上,在模型模型页面的getData函数上有数据,但是当我将数据发送到另一个页面时,数据返回为null。你能帮我吗?
//model.dart
import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
class Models {
var data;
Map jsondata = {};
var liste = new List();
Future<void> create(var table , data) async {
Firestore.instance.collection(table).document()
.setData(data).catchError((e){
print(e);
});
}
getData() async{
await Firestore.instance
.collection('musteri')
.document('-LgCmdigOCSqe9j-19lA')
.get()
.then((DocumentSnapshot datas) {
this.jsondata = datas.data;
});
return this.jsondata;
}
}
//chat.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:chat/menu/bottomMenu.dart';
import 'package:chat/models/models.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class Chat extends StatelessWidget {
QuerySnapshot snapshot;
Models model = new Models();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Chat"),
centerTitle: true,
),
body: datas(),
bottomNavigationBar: BottomMenu(),
);
}
datas() {
model.getData();
print(model.jsondata);
}
}
当我在getData中使用print(this.jsondata)时, 结果是{'name':'jhon','surname':'wick'}
但是chat.dart中的model.jsondata为空
答案 0 :(得分:0)
您的用户界面是在填充模型数据之前构建的。因此,一旦提取数据,您就需要重新构建。
class Models {
var data;
Map jsondata = {};
var liste = new List();
Future<Map> getData() async{
return Firestore.instance
.collection('musteri')
.document('-LgCmdigOCSqe9j-19lA')
.get()
.then((DocumentSnapshot datas) => datas.data);
}
}
class Chat extends StatefulWidget {
@override
_ChatState createState() => _ChatState();
}
class _ChatState extends State<Chat> {
QuerySnapshot snapshot;
Models _model;
Map _jsondata;
@override
void initState() {
super.initState();
_model = new Models();
_model.getData().then((data) {
setState(() {
_jsondata = data;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Chat"),
centerTitle: true,
),
body: _jsondata == null
? Container()
: Container(
child: Center(
child: Text(
_jsondata["name"],
),
),
),
// bottomNavigationBar: BottomMenu(),
);
}
}
尝试这样的事情。