一尘不染

Flutter 为什么不遵守容器宽度?

flutter

我正在尝试创建一个圆形图像。不幸的是,容器的宽度
不符合要求,我不知道为什么。我想念什么?

Drawer _getDrawer(List<Job> data) {
  return Drawer(
    // Add a ListView to the drawer. This ensures the user can scroll
    // through the options in the Drawer if there isn't enough vertical
    // space to fit everything.
    child: ListView(
      // Important: Remove any padding from the ListView.
      padding: EdgeInsets.zero,
      children: <Widget>[
        _getDrawerHeader(),
        ListTile(
          title: Text('Item 1'),
          onTap: () {
            // Update the state of the app
            // ...
          },
        ),
        ListTile(
          title: Text('Item 2'),
          onTap: () {
            // Update the state of the app
            // ...
          },
        ),
      ],
    ),
  );
}

DrawerHeader _getDrawerHeader() {
  return DrawerHeader(
    child: StreamBuilder(
        stream: FirebaseAuth.instance.currentUser().asStream(),
        builder: (context, AsyncSnapshot<FirebaseUser> snapshot) {
          if (snapshot.hasData) {
            return ListView(
              children: <Widget>[
                _getCircleImage(snapshot.data.photoUrl),
                Text('test'),
                Text('test'),
              ],
            );
          }
          return Center(child: CircularProgressIndicator());
        }),
    decoration: BoxDecoration(
      color: Colors.blue,
    ),
  );
}

_getCircleImage(String url) {
  return Container(
    width: 64.0,
    height: 64.0,
    decoration: new BoxDecoration(
      image: new DecorationImage(
        image: new NetworkImage(url),
        fit: BoxFit.cover,
      ),
      shape: BoxShape.circle,
    ),
  );
}

阅读 233

收藏
2020-08-13

共1个答案

一尘不染

这有点棘手,但这是Flutter的工作方式,您Container不知道Parent的约束,于是它尝试填充所有可用空间。

您可以添加Align小部件来修复它

    _getCircleImage(String url) {
      return Align(
        alignment: Alignment.centerLeft,
        child: Container(
          width: 64.0,
          height: 64.0,
          decoration: new BoxDecoration(
            image: new DecorationImage(
              image: new NetworkImage(url),
              fit: BoxFit.cover,
            ),
            shape: BoxShape.circle,
          ),
        ),
      );
    }

More info : https://docs.flutter.io/flutter/widgets/Container-class.html

2020-08-13