Flutter中async...await以及无状态和有状态的widget

2022年7月25日 998点热度 0人点赞 0条评论

1、async...await 返回的是Future,后面可以接then()

<code>import &#039;package:flutter/material.dart&#039;;

main(){
  renderSome();
}

request() async{
  await Future.delayed(const Duration(seconds: 2));
  return &quot;response&quot;;
}

doSomething() async{
  var result =  await request();
  result = &quot;OK response&quot;;
  return result;
}

renderSome(){
  doSomething().then((value){
    debugPrint(&quot;result:$value&quot;);
  });
}</code>

2、无状态和有状态的widget

<code>import &#039;package:flutter/material.dart&#039;;

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(&quot;无状态Widget&quot;),
          centerTitle: true,
        ),
        body:  const DemoStateWidget(),
      ),
    );
  }
}

class DomeWidget extends StatelessWidget {
  const DomeWidget(this.text,{Key? key}) : super(key: key);

  final String text;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Text(text),
    );
  }
}

class DemoStateWidget extends StatefulWidget {
  const DemoStateWidget({Key? key}) : super(key: key);

  @override
  State&lt;DemoStateWidget&gt; createState() =&gt; _DemoStateWidgetState();
}

class _DemoStateWidgetState extends State&lt;DemoStateWidget&gt; {

    String? text;

    @override
    void initState() {
    super.initState();

    //延迟两秒改变text数值
    Future.delayed(const Duration(seconds: 2),(){
      setState(() {
        text = &quot;这就变了数值&quot;;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(text ?? &quot;有状态的widget&quot;);
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint(&quot;dispose()&quot;);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    debugPrint(&quot;didChangeDependencies()&quot;);
  }
}</code>

小小调酒师

此刻打盹,你将做梦; 此刻学习,你将圆梦。 个人邮箱:shellways@foxmail.com

文章评论