【问题标题】:Add button on the screen without using MaterialApp Flutter在屏幕上添加按钮而不使用 MaterialApp Flutter
【发布时间】:2019-06-30 03:02:17
【问题描述】:

我正在尝试制作一个简单的示例,在 Flutter 的屏幕中心有一个可点击的按钮。我可以使用 MaterialApp 小部件来做到这一点,但我想在不使用 MaterialApp 的情况下做到这一点。

此示例适用于文本小部件

import 'package:flutter/material.dart';

void main() {
  runApp(
      Center(
      child: Text(
        'Hello, world!',
        textDirection: TextDirection.ltr,
      ),
    ),
  ) ;
}

但是我用 FlatButton 或 RaisedButton 更改 Text 小部件的所有尝试都失败了,因为它们依赖于 Material Widget

我也试过了:

import 'package:flutter/material.dart';

void main() {
  runApp(
      Container(
          decoration: BoxDecoration(color: Colors.white),
          child:Center(
      child: RaisedButton(
            child: const Text('Press meh', textDirection: TextDirection.ltr),
            onPressed: () {
            },
          ),
          )
      )
  );
}

问题是:有没有办法让Button不依赖于Material Widget?

【问题讨论】:

  • 喜欢吗?导入“包:颤振/material.dart”; void main() { runApp( Card( child: Center( child: FlatButton( child: Text( 'Hello, world!', textDirection: TextDirection.ltr, ), ), ) ) ); } 不工作

标签: flutter flutter-layout


【解决方案1】:

那么你必须使用 - WidgetsApp

void main() {
  runApp(SomeText());
}

class SomeText extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WidgetsApp(
      builder: (context, int) {
        return Center(
          child: RaisedButton(
            onPressed: () {},
            child: Text(
              'Hello, world!',
              textDirection: TextDirection.ltr,
            ),
          ),
        );
      },
      color: Colors.blue,
    );
  }
}

根据文档 -

WidgetsApp,定义了基本的app元素但不依赖 在材料库上。

更新 - 没有其他类:

如果你使用home:,那么你需要通过 - onGenerateRoutepageRouteBuilder

如果既没有提供 builder 也没有提供 onGenerateRoute,则 必须指定 pageRouteBuilder 以便默认处理程序将 知道要构建什么样的 PageRoute 过渡。

void main() {
  runApp(WidgetsApp(
    builder: (context, int) {
      return Center(
        child: RaisedButton(
          onPressed: () {},
          child: Text(
            'Hello, world!',
            textDirection: TextDirection.ltr,
          ),
        ),
      );
    },
    color: Colors.blue,
  ));
}

【讨论】:

  • 我们可以不单独上课吗?我的意思是我尝试了以下操作,但出现异常: void main() { runApp( WidgetsApp( home: Center( child: RaisedButton( onPressed: () {}, child: Text( 'Hello, world!', textDirection: TextDirection) .ltr, ), ), ) ) ); }
  • 谢谢它有效。但我不明白为什么我们需要这部分“ builder: (context, int) { return " 因为在文本的情况下,我们不需要它。
  • 因为 - 这个小部件有条件 - 'builder != null || onGenerateRoute != null || pageRouteBuilder != null': 所以你已经定义了它们中的任何一个来工作。
  • 我只是用builder
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
相关资源
最近更新 更多