Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

firebase - Problems with using a URL in NetworkImage (flutter)

I am trying to pass a URL that I receive from Firebase to my NetworkImage widget on the AppBar. However, my code keeps passing a null value to my NetworkImage widget. How can I pass the URL properly to the widget.

class DashboardScreen extends StatefulWidget {
  @override
  _DashboardScreenState createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen> {

  Future inputData() async {
    final FirebaseAuth auth = FirebaseAuth.instance;
    final FirebaseUser user = await auth.currentUser();
    final uid = user.uid;
    DocumentReference _stock = Firestore.instance.document('users/$uid');
    DocumentSnapshot snapshot = await _stock.get();
    Map<String, dynamic> data = snapshot.data;
    return data['image_url'];
  }

  String myAvatarUrl;

  void converter() {
    inputData().then((result) {
      myAvatarUrl = result;
      print(myAvatarUrl);
    });
  }

  @override
  Widget build(BuildContext context) {
    converter();
    return Scaffold(
      appBar: AppBar(
        leading: Padding(
          padding: EdgeInsets.only(top: 12.0, bottom: 12.0, left: 13.0),
          child: CircleAvatar(
            backgroundImage: NetworkImage(myAvatarUrl),
            child: FlatButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => SearchsettingsScreen(),
                  ),
                );
              },
            ),
            backgroundColor: Colors.white,
          ),
        ),
        centerTitle: true,
        title: Text(
          'My Dashboard',
        ),
        backgroundColor: Theme.of(context).primaryColor,
        automaticallyImplyLeading: false,
        actions: [
          DropdownButton(
            underline: Container(),
            icon: Icon(
              Icons.more_vert,
              color: Theme.of(context).primaryIconTheme.color,
            ),
            items: [
              DropdownMenuItem(
                child: Container(
                  child: Row(
                    children: <Widget>[
                      Icon(
                        Icons.exit_to_app,
                      ),
                      SizedBox(
                        width: 8.0,
                      ),
                      Text('Logout'),
                    ],
                  ),
                ),
                value: 'logout',
              ),
            ],
            onChanged: (itemIdentifier) {
              if (itemIdentifier == 'logout') {
                FirebaseAuth.instance.signOut();
              }
            },
          ),
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          ReusableDashboardSettingCard(),
          ReusableDashboardContactsCard(),
        ],
      ),
    );
  }
}

This is the error I get on my console:

The following assertion was thrown building DashboardScreen(dirty, state: _DashboardScreenState#e1615):
'package:flutter/src/painting/_network_image_io.dart': Failed assertion: line 26 pos 14: 'url != null': is not true.
question from:https://stackoverflow.com/questions/65844044/problems-with-using-a-url-in-networkimage-flutter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your main errors are:

  • you are not managing that there is the possibility that myAvatarUrl can be null
  • you are not telling to Flutter to rebuild your widget when data will arrive using setState((){})

I suggest you take a look at Codelabs and Fetch data from the internet.

I've not tested it but it should work

import 'package:flutter/material.dart';

class DashboardScreen extends StatefulWidget {
  @override
  _DashboardScreenState createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen> {
  String myAvatarUrl;

  Future inputData() async {
    final FirebaseAuth auth = FirebaseAuth.instance;
    final FirebaseUser user = await auth.currentUser();
    final uid = user.uid;
    DocumentReference _stock = Firestore.instance.document('users/$uid');
    DocumentSnapshot snapshot = await _stock.get();
    Map<String, dynamic> data = snapshot.data;
    return data['image_url'];
  }

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

    // When data will arrive
    inputData().then((value) {
      setState(() => myAvatarUrl = value);
      print(myAvatarUrl);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: myAvatarUrl == null
            ? const SizedBox()
            : Padding(
                padding: EdgeInsets.only(top: 12.0, bottom: 12.0, left: 13.0),
                child: CircleAvatar(
                  backgroundImage: NetworkImage(myAvatarUrl),
                  child: FlatButton(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => SearchsettingsScreen(),
                        ),
                      );
                    },
                  ),
                  backgroundColor: Colors.white,
                ),
              ),
        centerTitle: true,
        title: Text(
          'My Dashboard',
        ),
        backgroundColor: Theme.of(context).primaryColor,
        automaticallyImplyLeading: false,
        actions: [
          DropdownButton(
            underline: Container(),
            icon: Icon(
              Icons.more_vert,
              color: Theme.of(context).primaryIconTheme.color,
            ),
            items: [
              DropdownMenuItem(
                child: Container(
                  child: Row(
                    children: <Widget>[
                      Icon(
                        Icons.exit_to_app,
                      ),
                      SizedBox(
                        width: 8.0,
                      ),
                      Text('Logout'),
                    ],
                  ),
                ),
                value: 'logout',
              ),
            ],
            onChanged: (itemIdentifier) {
              if (itemIdentifier == 'logout') {
                FirebaseAuth.instance.signOut();
              }
            },
          ),
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          ReusableDashboardSettingCard(),
          ReusableDashboardContactsCard(),
        ],
      ),
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...