Получение данных Firebase во флаттере возвращает пустую строку - PullRequest
0 голосов
/ 02 августа 2020

Я создал 2 переменные (nameUserDisplay и aboutUserDisplay), когда данные извлекаются с помощью метода _getName () и _getAbout (). Возвращается пустая строка.

В проекте требуется, чтобы данные в документе отображались вместо любых данных по умолчанию.

Пожалуйста, помогите.

Ниже приведено полный код

class UserScreen extends StatefulWidget {
  final User currentUser;

  UserScreen({this.currentUser});

  @override
  _UserScreenState createState() => _UserScreenState();
}

class _UserScreenState extends State<UserScreen> {
  String nameUserDisplay;
  String aboutUserDisplay;

  void _getName() async {
    Firestore.instance
        .collection("userInfo")
        .document(widget.currentUser.email)
        .get()
        .then((value) {
      nameUserDisplay = value.data["name"].toString();
      print(nameUserDisplay);
    });
  }

  void _getAbout() async {
    Firestore.instance
        .collection("userInfo")
        .document(widget.currentUser.email)
        .get()
        .then((value) {
      aboutUserDisplay = value.data["about"].toString();
      print(aboutUserDisplay);
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getAbout();
    _getName();
  }

  @override
  Widget build(BuildContext context) {
//    if (nameUserDisplay == null) nameUserDisplay = 'Sanatani';

//    if (aboutUserDisplay == null)
//      aboutUserDisplay = 'A Sanatana Dharma Follower';

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: Colors.white,
            ),
            onPressed: () {
              // do something
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => BlogScreen(
                    currentUser: widget.currentUser,
                  ),
                ),
              );
            },
          )
        ],
        title: Text('You'),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: <Color>[Colors.orange, Colors.red],
            ),
          ),
        ),
      ),
      body: WillPopScope(
        onWillPop: () async {
          return Future.value(false);
        },
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              SizedBox(height: 20),
              Flexible(child: Image.asset('assets/images/hoilogo.png')),
              SizedBox(height: 40),
              Container(
                child: Text(
                  nameUserDisplay,
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                ),
              ),
              SizedBox(height: 20),
              Container(
                padding: EdgeInsets.only(left: 8, right: 8),
                child: Text(
                  aboutUserDisplay,
                  style: TextStyle(fontSize: 15),
                  textAlign: TextAlign.center,
                ),
              ),
              Flexible(child: SizedBox(height: 940)),
              FlatButton(
                child: Text(
                  'Add/Edit your profile Details',
                  style: TextStyle(
                      color: Colors.orange, fontWeight: FontWeight.bold),
                ),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => UserEditDetails(
                        currentUser: widget.currentUser,
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Firebase - это платформа для создания мобильных и веб-приложений, разработанная Google. Изначально это была независимая компания, основанная в 2011 году. В 2014 году платформу приобрела Google, и теперь она является их флагманским предложением для разработки приложений. Я использовал его как базу данных.

1 Ответ

1 голос
/ 02 августа 2020

Вам нужно вызвать setState, когда вы получите имя и собираетесь принудительно перестроить виджеты с новыми значениями состояния.

Кроме того, похоже, что вы могли бы сделать обе вещи одним и тем же методом, чтобы избежать позвонив по номеру setState дважды, так как это не бесплатно.

void _getData() {
    Firestore.instance
        .collection("userInfo")
        .document(widget.currentUser.email)
        .get()
        .then((value) =>
            setState((){
                aboutUserDisplay = value.data["about"].toString();
                nameUserDisplay = value.data["name"].toString();
            }));
}
...