美文网首页
flutter-开发中,各种组件的应用场景【二】

flutter-开发中,各种组件的应用场景【二】

作者: 青菜白玉堂 | 来源:发表于2022-08-15 15:29 被阅读0次

    Container组件嵌套chid【Container】,chid【Container】大小调整技巧

    场景:有一个全局大小的父Container设置背景色,内部有一个子Container负责装配各种组件,有另一种背景色,且需随装配的组件自适应大小【用于弹出式遮盖层的布局】
    问题:子Container会跟随父Container大小,无法自适应
    技巧:如代码所示,使用Stack【或者Column,Algin,Center等组件】包一层

    Container(
          width: ToolScreenWidth,
          height: ToolScreenHeight,
          color: Color.fromRGBO(0, 0, 0, 0.5),
          child: Stack(
            children: [
              Container(
                color: Colors.white,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    SizedBox(height: ToolStatusBarHeight,),
                    Container(
                      width: ToolScreenWidth,
                      height: 70,
                      color: Colors.red,
                    ),
                    Container(
                      width: ToolScreenWidth,
                      height: 70,
                      color: Colors.yellow,
                    ),
                    Container(
                      width: ToolScreenWidth,
                      height: 90,
                      color: Colors.greenAccent,
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
    

    键盘遮盖输入框问题

    场景:在键盘弹出时需要在键盘上附加一个工具view【Container】,在输入框【TextField】外层套一个滚动组件【SingleChildScrollView】,默认输入框会处理键盘遮盖问题【自动向上滚动】,但无法处理工具view的遮盖,在这里需要监听键盘的滚动事件,以及工具view的位置,和输入框的位置以及滚动组件的滚动位置,计算出差值,进行滚动。

    输入框遮挡方案
    ///基础
    import 'package:flutter/material.dart';
    import 'package:firstproject/app/AppBarCustomBase.dart';
    
    ///工具
    import 'package:firstproject/until/Tool.dart';
    
    class CrosswordGameSetingPage extends StatefulWidget {
      final arguments;
    
      CrosswordGameSetingPage({this.arguments, Key? key}) : super(key: key) {
        print("看看页面参数---${this.arguments}");
      }
    
      @override
      State<CrosswordGameSetingPage> createState() =>
          _CrosswordGameSetingPageState();
    }
    
    class _CrosswordGameSetingPageState extends State<CrosswordGameSetingPage> with WidgetsBindingObserver {
    
      ScrollController _bgScrController = ScrollController();
      ///工具UI-GlobalKey
      GlobalKey _toolViewlKey = GlobalKey();
      ///输入框
      GlobalKey _filelKey = GlobalKey();
    
      ///初始化方法
      void initState() {
        super.initState();
    
        //监听滚动事件,打印滚动位置
        _bgScrController.addListener(() {
          print("滚动位置变化--${_bgScrController.offset}"); //打印滚动位置
        });
    
        ///监听键盘高度变化
        WidgetsBinding.instance.addObserver(this);
    
      }
    ///在页面高度发生变化的时候会触发该回调
      @override
      void didChangeMetrics() {
        super.didChangeMetrics();
        WidgetsBinding.instance.addPostFrameCallback((_) {
          print('键盘高度---${MediaQuery.of(context).viewInsets.bottom}');
        });
      }
    
      ///析构
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
      Widget _getBodyWidget(BuildContext context) {
        
        return Container(
          width: ToolScreenWidth,
          height: ToolScreenHeight,
          color: Colors.white,
          child: Stack(
            alignment: Alignment.topCenter,
            children: [
              Positioned(
                child:Container(
                  width: ToolScreenWidth,
                  height: ToolScreenHeight,
                  color: ToolColorRandomColor(),
                  child: SingleChildScrollView(
                      controller: _bgScrController,
                    child:Column(
                      children: [
                        Container(
                          width: ToolScreenWidth,
                          height: 300,
                          color: ToolColorRandomColor(),
                        ),
                        Container(
                          width: ToolScreenWidth,
                          height: 200,
                          color: ToolColorRandomColor(),
                        ),
                        Container(
                          width: ToolScreenWidth,
                          height: 40,
                          child: TextField(
                            key: _filelKey,
                            controller: TextEditingController(text: "输入框"),
                            onTap: (){
                              judgeKeyboardOverspreadTextFile();
                            },
                          ),
                        ),
                        Container(
                          width: ToolScreenWidth,
                          height: 200,
                          color: ToolColorRandomColor(),
                        ),
    
                      ],
                    )),
                ),
    
              ),
              Positioned(
                bottom: 0,
                child: Container(
                  key: _toolViewlKey,
                  width: ToolScreenWidth,
                  height: 100,
                  color: Color.fromRGBO(0, 0, 0, 0.5),
                  child: Text("工具栏"),
                ),
              )
            ],
          ),
        );
      }
    
    
      ///处理键盘遮盖问题
      void judgeKeyboardOverspreadTextFile() {
        Future.delayed(Duration(milliseconds: 800), () {
          final toolViewBox =
          this._toolViewlKey.currentContext?.findRenderObject() as RenderBox?;
          double boxY = toolViewBox?.localToGlobal(Offset.zero).dy ?? 0;
    
          print(
              "我想看看--提示view位置---${toolViewBox?.localToGlobal(Offset.zero)}---${toolViewBox?.size}");
    
          GlobalKey filelKey = _filelKey;
          final filebox = filelKey.currentContext?.findRenderObject() as RenderBox?;
          double fileboxY = filebox?.localToGlobal(Offset.zero).dy ?? 0;
          double fileboxHeight = filebox?.size.height ?? 0;
          print(
              "我想看看--file位置---${filebox?.localToGlobal(Offset.zero)}---${filebox?.size}");
    
          if (fileboxY + fileboxHeight >= boxY) {
            double? scroY =
                fileboxY - boxY + fileboxHeight + _bgScrController.offset + 10;
            this._bgScrController.animateTo(
              scroY,
              duration: Duration(milliseconds: 200),
              curve: Curves.ease,
            );
            print("我想看看--滚动位置---${scroY}---");
          }
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: RawKeyboardListener(
            autofocus: true,
            onKey: (event) {
              print("键盘----event=${event.toString()}");
            },
            focusNode: FocusNode(),
            child: _getBodyWidget(context),
          ),
          appBar: AppBarCustomBase(
            barHeight: 100,
            backgroundImageName: 'assets/images/bg_375x90.png',
            leadingWidget: GestureDetector(
              child: Image.asset(
                'assets/images/icon_back.png',
                width: 66,
                height: 41,
                fit: BoxFit.cover,
              ),
              onTap: () {
                Navigator.of(context).pop();
              },
            ),
            trailingWidget: Image.asset(
              'assets/images/icon_share.png',
              width: 66,
              height: 41,
            ),
          ),
        );
      }
    }
    
    

    相关文章

      网友评论

          本文标题:flutter-开发中,各种组件的应用场景【二】

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