【问题标题】:How to Change State of Material Button after a Delay?延迟后如何更改材质按钮的状态?
【发布时间】:2021-07-12 02:41:37
【问题描述】:

我有一个 Emojis 列表,[????, ????, ????????, ????????, ????????, ????????, ????????, ????, ????, ????, ????, ????, ????, ????] 和我在一起,我也有一个没有与之关联的图标的按钮。请参阅此材质按钮。

                     MaterialButton(
                        onPressed: () {},
                        
                        child: Text("",textScaleFactor: 2),
                        shape: CircleBorder(),
                        padding: EdgeInsets.all(16),
                      ),

现在,我需要在延迟 1 秒后在此按钮内显示上述列表 [????, ????, ????????, ????????, ????????, ????????, ????????, ????, ????, ????, ????, ????, ????, ????]

【问题讨论】:

标签: flutter dart flutter-dependencies flutter-test flutter-text


【解决方案1】:

你也可以使用 Future。

MaterialButton(
 onPressed: () async {
     await Future<void>.delayed(Duration(seconds: 1));
     // your function
     },
 child: Text('', textScaleFactor: 2),
 shape: CircleBorder(),
 padding: EdgeInsets.all(16),
),

【讨论】:

  • 所以我需要将我的 For 循环或其他东西放在 Davor 的代码指定的 await 事物的下方?
  • 你能解释一下吗,我怎样才能在 Material Button 中的 Icon 的地方一一显示列表
【解决方案2】:

您可以使用 Timer.periodic 来实现这一点。请参阅此示例代码

Link to docs


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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Timer emojiTimer;

  @override
  void initState() {
    emojiTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      changeEmoji();
    });
    super.initState();
  }

  int randomInt = 0;
  Future<void> changeEmoji() async {
    setState(() {
      var ran = Random();
      randomInt = ran.nextInt(emojiList.length);
    });
  }

  var emojiList = [
    "?",
    "?",
    " ??",
    "??",
    " ??",
    " ??",
    "??",
    "?",
    "?",
    "?",
    "?",
    "?",
    "?",
    "?"
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Text('hello there'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          emojiTimer.cancel();
        },
        child: Text(emojiList[randomInt]),
      ),
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-09
    • 2013-12-06
    • 1970-01-01
    • 2019-08-27
    • 2020-11-22
    • 2019-06-03
    • 2020-02-24
    相关资源
    最近更新 更多