Исключение платформы Flutter в FutureBuilder - PullRequest
1 голос
/ 21 июня 2020

Я получаю следующее исключение PlatformException в FutureBuilder при запуске app.release.apk на телефоне Android. Это происходит не каждый раз.

Я заметил, что если у меня открыто приложение и я закрываю телефон, после открытия и посещения первого элемента из ListView отображается ошибка, иногда после посещения другие элементы вызывают исключение, иногда нет.

PlatformException(Error performing get, Failed to get document because the client is offline., null

class _ItemState extends State<Item> {

  Future _itemFuture;


 @override
  void initState() {

  setState(() {
    _itemFuture = Firestore.instance
      .collection('content')
      .document(widget.item.documentID)
      .get();
  });
  ...

  super.initState();
}

Scaffold( 
  body: Container(
    child: FutureBuilder<DocumentSnapshot>(
      future: _itemFuture,
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
            return Container();
          case ConnectionState.waiting:
            return Center(
              child: CircularProgressIndicator(),
            );
          default:
            if (snapshot.hasError) {
              return Text('Error1: ${snapshot.error}');
            } else {
              if (snapshot.hasData) {
                return _itemBody(
                  snapshot.data,
                );
              }
            }
            return null;
        }
      },
    ),
  ),
);

Я использую:

cloud_firestore: ^0.13.7
firebase_auth: ^0.16.1

*** Изменить

Я добавлю весь виджет. Я почистил его, удалив все остальные logi c, которые, как я думал, могли вызвать ошибку. Теперь это минимальный виджет, который делает запрос в Firestore с помощью Streambuilder. Конечно с такой же ошибкой.

class Item extends StatefulWidget {
  Item({
    Key key,
    this.items,
    this.showAd,
    this.user,
    this.item,
    this.favorites,
  }) : super(key: key);
  final List<Imodel> items;
  final bool showAd;
  final UserModel user;
  final item;
  final List<FireFavorites> favorites;

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

class _ItemState extends State<Item> {
  DateTime _lastViewed;
  bool _viewRequest = true;
  final _adWidget = AdMobWidget();
  bool _favoriteItem = false;

  @override
  void initState() {
    super.initState();

    final isFavorite = widget.favorites
        .where((element) => element.id == widget.item.documentID);

    if (isFavorite.length > 0) {
      _favoriteItem = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.showAd) {
      _adWidget.showAd();
    }

    final _headerStyle = TextStyle(fontWeight: FontWeight.bold);

    Widget _itemBody(item) {
      return ListView(
        children: <Widget>[
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
             ...
            ],
          ),
        ],
      );
    }

    _future() {
      return FutureBuilder<DocumentSnapshot>(
        future: Firestore.instance
            .collection('content')
            .document(widget.item.documentID)
            .get(source: Source.serverAndCache),
        builder:
            (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
          List<Widget> children;
          if (snapshot.hasData) {
            children = <Widget>[Expanded(child: _itemBody(snapshot.data))];
          } else if (snapshot.hasError) {
            children = <Widget>[
              Icon(
                Icons.error_outline,
                color: Colors.red,
                size: 60,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 16),
                child: Text('Error: ${snapshot.error}'),
              )
            ];
          } else {
            children = <Widget>[
              SizedBox(
                child: CircularProgressIndicator(),
                width: 60,
                height: 60,
              ),
              const Padding(
                padding: EdgeInsets.only(top: 16),
                child: Text('Awaiting result...'),
              )
            ];
          }
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: children,
            ),
          );
        },
      );
    }

    return Scaffold(
      resizeToAvoidBottomPadding: false,
      backgroundColor: Color(0xff2398C3),
      appBar: AppBar(
        elevation: 0,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Color(0xff042C5C), Color(0xff2398C3)],
            ),
          ),
        ),
        actions: <Widget>[
          BookmarkIcon(
            isFav: _favoriteItem,
            documentID: widget.item.documentID,
            userID: widget.user.uid,
          ),
          Padding(
            padding: EdgeInsets.only(
              right: 20.0,
            ),
            child: GestureDetector(
              onTap: () {},
              child: Icon(
                Icons.share,
                size: 18.0,
              ),
            ),
          ),
        ],
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.only(
          top: 25.0,
          left: 30.0,
          right: 15.0,
        ),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(32),
            topRight: Radius.circular(32),
          ),
        ),
        child: widget.item.documentID != null ? _future() : Container(),
      ),
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...