【问题标题】:why ListView must be wrapped by MaterialApp?为什么ListView必须被MaterialApp包裹?
【发布时间】:2020-03-04 12:01:59
【问题描述】:

想知道为什么在flutter中,Listview和Text不同,不能直接返回到runApp()

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ListView(
        padding: const EdgeInsets.all(8),
        children: <Widget>[
          Container(
            height: 50,
            color: Colors.amber[600],
            child: const Center(child: Text('Entry A')),
          ),
        ],
      ),
    );
  }
}

如果 ListView 包装在 MaterialApp 中,它可以工作。但是,如果它是直接返回或在容器中返回,如下所示:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: ListView(
        padding: const EdgeInsets.all(8),
        children: <Widget>[
          Container(
            height: 50,
            color: Colors.amber[600],
            child: const Center(child: Text('Entry A')),
          ),
        ],
      ),
    );
  }
}

我有错误。 我已经阅读了很多关于颤振的文章,包括官方文档的 Listview api,但没有人解释原因。虽然有人在 github(https://github.com/flutter/flutter/issues/50947) 中提交了问题,但解决者只告诉他如何解决问题而没有理由。

【问题讨论】:

    标签: listview flutter


    【解决方案1】:

    ListView 期望定义文本方向。 MaterialApp 正在为您定义,但如果您不想使用它 - 您可以使用 Directionality 自己做。

    ListView 需要该属性来计算滚动的方式。

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Directionality(textDirection: TextDirection.ltr, child: ListView(
          children: <Widget>[
            Text('Row One'),
            Text('Row Two'),
            Text('Row Three'),
            Text('Row Four'),
          ],
        ));
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 1970-01-01
      • 2015-05-31
      • 2021-05-12
      • 1970-01-01
      • 2016-02-13
      • 2018-08-18
      相关资源
      最近更新 更多