Flutter小问题及其解决方案

本文章随缘更新,希望对你有帮助。

1. 使用InkWell包裹的组件作为ListView的子组件会溢出

我们有以下界面

 ListView.builder(
  padding: const EdgeInsets.all(16.0),
  itemBuilder: (context, index) {
    return Ink(
      color: Colors.primaries[index%Colors.primaries.length],
      child: InkWell(
        onTap: (){},
        child: Container(height: 64),
      ),
    );
  },
)

image

我们可以发现,虽然我们已经设置了padding属性,但是列表还是调皮的超出了界限。这个时候,只要我们把InkInkWellMaterial包裹起来,就可以解决这个问题。

ListView.builder(
  padding: const EdgeInsets.all(16.0),
  itemBuilder: (context, index) {
    return Material(
      child: Ink(
        color: Colors.primaries[index%Colors.primaries.length],
        child: InkWell(
          onTap: (){},
          child: Container(
            height: 64,
          ),
        ),
      ),
    );
  },
),

image

2. url_launcher 无法打开中文路径

在 PC 端我们可以使用 url_launcher 来打开文件浏览器的某个文件夹,例如:

void openFolder(String fileFolder) async {
  final Uri url = Uri.parse('file:/$fileFolder');
  if (await canLaunchUrl(url)) {
    await launchUrl(url);
  } else {
    throw '无法打开文件夹:$fileFolder';
  }
}

当我们传入的 fileFolder 是纯英文路径的时候,可以很轻松打开文件夹。如果传入的是非英文路径,会得到类似如下的错误:

flutter: 错误:PlatformException(open_error, Failed to open file:///E:/%E6%96%B0%E5%BB%BA%E6%96%87%E4%BB%B6%E5%A4%B9: ShellExecute error code 2, null, null)

要想修正改错误,可更改代码如下:

void openFolder(String fileFolder) async {
  String encodedPath = Uri.encodeComponent(fileFolder);
  if (Platform.isWindows) {
    await Process.run('explorer', [fileFolder]);
  } else {
    final Uri url = Uri.parse('file:///${encodedPath.replaceAll(' ', '%20')}');
    if (await canLaunchUrl(url)) {
      await launchUrl(url);
    } else {
      debugPrint('无法打开文件夹:$fileFolder');
    }
  }
}
posted @ 2022-09-23 11:22  菠萝橙子丶  阅读(213)  评论(0编辑  收藏  举报