美文网首页
Flutter 2开发

Flutter 2开发

作者: 落寞1990 | 来源:发表于2023-08-16 09:56 被阅读0次

    1、AlertDialog

    showDialog(
           context: context,
           builder: (context) {
             return AlertDialog(
               title: const Text("标题"),
               content: const Text("您确定要删除么?"),
               actions: <Widget>[
                 TextButton(
                     onPressed: () {
                       Navigator.of(context).pop();
                     },
                     child: const Text("取消")),
                 TextButton(
                     onPressed: () {
                       Navigator.of(context).pop();
                     },
                     child: const Text("确定")),
               ],
             );
           });
    

    2、SimpleDialogOption

    showDialog(
           context: context,
           builder: (context) {
             return SimpleDialog(
               title: const Text("第二标题"),
               children: [
                 SimpleDialogOption(
                   child: const Text("日语"),
                   onPressed: () {
                     Navigator.of(context).pop();
                   },
                 ),
                 SimpleDialogOption(
                   child: const Text("日语"),
                   onPressed: () {
                     Navigator.of(context).pop();
                   },
                 ),
                 SimpleDialogOption(
                   child: const Text("法语"),
                   onPressed: () {
                     Navigator.of(context).pop();
                   },
                 )
               ],
             );
           });
    

    3、showModalBottomSheet

    showModalBottomSheet(
           context: context,
           builder: (context) {
             return const SizedBox(
               height: 250,
               child: Column(children: <Widget>[
                 ListTile(
                   title: Text("旅游"),
                 ),
                 Divider(),
                 ListTile(
                   title: Text("头条"),
                 ),
                 Divider(),
                 ListTile(
                   title: Text("热门"),
                 )
               ]),
             );
           });
    

    4、自定义dialog

    class myDialog extends Dialog {
     final String title;
     final String content;
     Function()? onCloseds;
     myDialog({super.key,required this.title,required this.content,required this.onCloseds});
     @override
     Widget build(BuildContext context) {
       return Material(
         type: MaterialType.transparency,
         child: Center(
           child: Container(
             height: 300,
             width: 300,
             color: Colors.white,
             child: Column(
               children: <Widget>[
                 Padding(
                   padding: const EdgeInsets.all(10),
                   child: Stack(
                     children: [
                       Align(
                         alignment: Alignment.topLeft,
                         child: Text(title),
                       ),
                       Align(
                         alignment: Alignment.topRight,
                         child: InkWell(
                           onTap: onCloseds,
                           child: const Icon(Icons.delete),
                         ),
                       )
                     ],
                   ),
                 ),
                 Container(
                   padding: const EdgeInsets.all(10),
                   width: double.infinity,
                   child: Text(content),
                 )
               ],
             ),
           ),
         ),
       );
     }
    }
    
    showDialog(
           barrierDismissible: false,
           context: context,
           builder: (context) {
             return myDialog(
               title: "测试2",
               content: "厉害2",
               onCloseds: () {
                 Navigator.of(context).pop();
               },
             );
           });
    

    5、轮播图+定时器+缓存

    class PagerViewPage extends StatefulWidget {
      const PagerViewPage({super.key});
    
      @override
      State<PagerViewPage> createState() => _PagerViewState();
    }
    
    class _PagerViewState extends State<PagerViewPage> {
      List<Widget> list = [];
      List imgData = [
        "https://www.itying.com/images/flutter/1.png",
        "https://www.itying.com/images/flutter/2.png",
        "https://www.itying.com/images/flutter/3.png"
      ];
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
        for (var i = 0; i < imgData.length; i++) {
    //缓存PicturePage,不要缓存可以不包裹KeepAliveWrapper,直接PicturePage
          list.add(KeepAliveWrapper(
              keepAlive: true, child: PicturePage(url: imgData[i])));
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: const Text("轮播图")),
          body: ListView(
            children: [Swiper(pageList: list)],
          ),
        );
      }
    }
    
    class Swiper extends StatefulWidget {
      double width;
      double height;
      List<Widget> pageList;
    
      Swiper(
          {super.key,
          this.width = double.infinity,
          this.height = 200,
          required this.pageList});
    
      @override
      State<Swiper> createState() => _SwiperState();
    }
    
    class _SwiperState extends State<Swiper> {
      int currentIndexS = 0;
      late PageController pageController;
      late Timer timer;
      @override
      void initState() {
        super.initState();
        pageController = PageController(initialPage: 0);
        timer = Timer.periodic(Duration(seconds: 3), (timer) {
          pageController.animateToPage((currentIndexS + 1) % widget.pageList.length,
              duration: Duration(milliseconds: 200), curve: Curves.linear);
        });
      }
    
      @override
      void dispose() {
        super.dispose();
    // 需要释放
        timer.cancel();
        pageController.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Stack(
          children: [
            SizedBox(
              width: widget.width,
              height: widget.height,
              child: PageView.builder(
                  controller: pageController,
                  itemCount: 1000,
                  onPageChanged: (int index) {
                    setState(() {
                      currentIndexS = index % widget.pageList.length;
                    });
                  },
                  itemBuilder: ((context, index) {
                    return widget.pageList[index % widget.pageList.length];
                  })),
            ),
            Positioned(
                left: 0,
                right: 0,
                bottom: 5,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: List.generate(widget.pageList.length, (i) {
                    return Container(
                      margin: const EdgeInsets.fromLTRB(0, 0, 5, 0),
                      width: 10,
                      height: 10,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: currentIndexS == i ? Colors.blue : Colors.grey,
                      ),
                    );
                  }).toList(),
                ))
          ],
        );
      }
    }
    
    class PicturePage extends StatefulWidget {
      double width;
      double height;
      String url;
      PicturePage({super.key,this.width = double.infinity,this.height = 200, required this.url});
    
      @override
      State<PicturePage> createState() => _PicturePageState();
    }
    
    class _PicturePageState extends State<PicturePage> {
      @override
      Widget build(BuildContext context) {
        print(widget.url);
        return SizedBox(
          width: widget.width,
          height: widget.height,
          child: Image.network(
            widget.url,
            fit: BoxFit.cover,
          ),
        );
      }
    }
    

    6、Flutter Key详解
    在Flutter中,Key是不能重复使用的,所以Key一般用来做唯一标识。组件在更新的时候,其状态的保
    存主要是通过判断组件的类型或者key值是否一致。因此,当各组件的类型不同的时候,类型已经足够
    用来区分不同的组件了,此时我们可以不必使用key。但是如果同时存在多个同一类型的控件的时候,
    此时类型已经无法作为区分的条件了,我们就需要使用到key。
    Flutter key子类包含 LocalKey 和 GlobalKey 。
    局部键(LocalKey):ValueKey、ObjectKey、UniqueKey
    全局键(GlobalKey): GlobalKey、GlobalObjectKey
    ValueKey (值key)把一个值作为key ,UniqueKey(唯一key)程序生成唯一的Key,当我们不知道
    如何指定ValueKey的时候就可以使用UniqueKey,ObjectKey(对象key)把一个对象实例作为key。
    GlobalKey(全局key),GlobalObjectKey(全局Objec key,和ObjectKey有点类似。
    比如使用了LocalKey,当屏幕状态改变的时候把 Colum换成了Row,Box的状态就会丢失,把LocalKey换成GlobalKey即可解决这个问题。

    final GlobalKey globalKey = GlobalKey();
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          floatingActionButton: FloatingActionButton(
              child: const Icon(Icons.add),
              onPressed: () {
                var state = globalKey.currentState as _BoxState;
                setState(() {
                  state.count++;
                });
              }),
          appBar: AppBar(title: const Text("key")),
          body: Center(
            child: Box(
              key: globalKey,
            ),
          ),
        );
      }
    

    相关文章

      网友评论

          本文标题:Flutter 2开发

          本文链接:https://www.haomeiwen.com/subject/lnukmdtx.html