Flutter PlatformException in FutureBuilder

假装没事ソ 提交于 2020-08-09 10:51:05

问题


I'm getting the below PlatformException in a FutureBuilder when running app.release.apk on an Android phone. It doesn't happen every time.

I noticed that if I have the app open and I close the phone, after opening it and visiting the first item from a ListView shows the error, sometimes following visits to other items causes the exception, sometimes not.

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;
        }
      },
    ),
  ),
);

I am using:

cloud_firestore: ^0.13.7
firebase_auth: ^0.16.1

*** Edit

I will add the whole widget. I cleaned it, removing any other logic that I thought might cause the error. Now it's a minimal widget that makes a request to Firestore using Streambuilder. Of course with the same error.

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(),
      ),
    );
  }
}

来源:https://stackoverflow.com/questions/62498796/flutter-platformexception-in-futurebuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!