Flutter响应式设计插件flutter_responsiveness的使用

Flutter响应式设计插件flutter_responsiveness的使用

flutter_responsiveness 是一个用于使应用具有响应式的新的Flutter包。响应式应用会根据屏幕或窗口的大小和形状来调整其用户界面。这在应用可以在多种设备上运行时尤为重要,从手表到手机、平板电脑,再到笔记本电脑或台式机。当用户在笔记本或台式机上调整窗口大小,或者改变手机或平板电脑的方向时,应用应相应地重新排列用户界面。

支持项目

如果您喜欢这个项目,请给它点个星以支持我们。

截图和GIF

使用方法

请参考 示例代码

添加依赖

要使用此包,请在 pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_responsiveness:

如何使用

首先,初始化 ScreenSize 以使其具有响应性。该函数通过以下方式初始化屏幕:

  • initialHeightinitialWidth 是您默认设置的应用程序屏幕布局的高度和宽度。
  • 假设您正在使用Google Pixel 3a进行开发,则它将成为开发应用程序的默认手机。确保输入初始高度和宽度以实现响应式。
  • widthheight 参数是 MediaQuery 参数,它们将帮助应用实现响应式。
@override
void initState() {
  super.initState();
  WidgetsBinding.instance.addPostFrameCallback((_) {
    ScreenSize(
      initialHeight: 759.2727272727273, // 对于Google Pixel 2XL,高度为823
      initialWidth: 392.72727272727275, // 对于Google Pixel 2XL,宽度为411
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
    );
  });
}

示例代码

import 'package:flutter/material.dart';
import 'package:flutter_responsiveness/flutter_responsiveness.dart';

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

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

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

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

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  int _counter = 0;

  AnimationController? _controller;
  Animation? _animation;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ScreenSize(
        initialHeight: 759.2727272727273,
        initialWidth: 392.72727272727275,
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
      );
    });

    _controller = AnimationController(vsync: this, duration: Duration(seconds: 2));
    _animation = Tween(
            begin: 0.0 * ScreenSize.heightMultiplyingFactor!,
            end: 300.0 * ScreenSize.heightMultiplyingFactor!)
        .animate(_controller!)
      ..addStatusListener((state) {
        if (state == AnimationStatus.completed) {
          print("completed");
        } else if (state == AnimationStatus.dismissed) {
          print("dismissed");
        }
      })
      ..addListener(() {
        print("value:${_animation!.value}");
        setState(() {});
      });
    _controller!.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            FlutterLogo(
              textColor: Colors.purple,
              size: 100.0 * ScreenSize.heightMultiplyingFactor!,
            ),
            AnimatedContainer(
              width: 300.0 * ScreenSize.widthMultiplyingFactor!,
              height: _animation!.value,
              curve: Curves.easeIn,
              duration: Duration(seconds: 5),
              color: Colors.amber,
            ),
            SizedBox(
              height: 10.0 * ScreenSize.heightMultiplyingFactor!,
            ),
            Container(
              color: Colors.redAccent,
              height: 100.0 * ScreenSize.heightMultiplyingFactor!,
              width: 100.0 * ScreenSize.widthMultiplyingFactor!,
            ),
            SizedBox(
              height: 30.0 * ScreenSize.heightMultiplyingFactor!,
            ),
            Text(
              'You have pushed the button this many times:',
              style: TextStyle(
                fontSize: 16.0 * ScreenSize.heightMultiplyingFactor!,
              ),
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(
          Icons.add,
          size: 46 * ScreenSize.heightMultiplyingFactor!,
        ),
      ),
    );
  }
}

许可证

MIT License

Copyright (c) 2020 DC0202

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

更多关于Flutter响应式设计插件flutter_responsiveness的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter响应式设计插件flutter_responsiveness的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中实现响应式设计是一个常见的需求,特别是当应用需要在不同尺寸的设备上保持良好的用户体验时。虽然没有一个官方的 flutter_responsiveness 插件,但你可以使用一些现有的包来实现响应式设计,或者自己编写代码来处理不同屏幕尺寸。

常用的响应式设计方法

  1. 使用 MediaQuery MediaQuery 是 Flutter 提供的一个内置类,用于获取设备屏幕的尺寸、方向等信息。你可以根据这些信息来动态调整布局。

    import 'package:flutter/material.dart';
    
    class ResponsiveLayout extends StatelessWidget {
      [@override](/user/override)
      Widget build(BuildContext context) {
        final screenWidth = MediaQuery.of(context).size.width;
        final screenHeight = MediaQuery.of(context).size.height;
    
        if (screenWidth > 600) {
          return TabletLayout();
        } else {
          return MobileLayout();
        }
      }
    }
    
    class MobileLayout extends StatelessWidget {
      [@override](/user/override)
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('Mobile Layout')),
          body: Center(child: Text('This is a mobile layout')),
        );
      }
    }
    
    class TabletLayout extends StatelessWidget {
      [@override](/user/override)
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('Tablet Layout')),
          body: Center(child: Text('This is a tablet layout')),
        );
      }
    }
    
  2. 使用 LayoutBuilder LayoutBuilder 可以根据父容器的尺寸来动态调整子组件的布局。

    import 'package:flutter/material.dart';
    
    class ResponsiveLayout extends StatelessWidget {
      [@override](/user/override)
      Widget build(BuildContext context) {
        return LayoutBuilder(
          builder: (context, constraints) {
            if (constraints.maxWidth > 600) {
              return TabletLayout();
            } else {
              return MobileLayout();
            }
          },
        );
      }
    }
    
  3. 使用 OrientationBuilder OrientationBuilder 可以根据设备方向来调整布局。

    import 'package:flutter/material.dart';
    
    class ResponsiveLayout extends StatelessWidget {
      [@override](/user/override)
      Widget build(BuildContext context) {
        return OrientationBuilder(
          builder: (context, orientation) {
            if (orientation == Orientation.portrait) {
              return PortraitLayout();
            } else {
              return LandscapeLayout();
            }
          },
        );
      }
    }
    
  4. 使用第三方包 有一些第三方包可以帮助你更轻松地实现响应式设计,例如:

    • flutter_screenutil: 可以根据屏幕尺寸自动调整字体大小、边距等。
    • responsive_framework: 提供了一个框架来帮助你管理响应式布局。
    • responsive_builder: 提供一个简单的API来创建响应式布局。

    例如,使用 flutter_screenutil

    dependencies:
      flutter_screenutil: ^5.0.0
    
    import 'package:flutter/material.dart';
    import 'package:flutter_screenutil/flutter_screenutil.dart';
    
    class ResponsiveLayout extends StatelessWidget {
      [@override](/user/override)
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Responsive Layout'),
          ),
          body: Center(
            child: Container(
              width: 200.w,
              height: 100.h,
              color: Colors.blue,
              child: Center(
                child: Text(
                  'Responsive Text',
                  style: TextStyle(fontSize: 20.sp),
                ),
              ),
            ),
          ),
        );
      }
    }
    

自定义响应式设计

你也可以根据项目的需求自定义响应式设计策略。例如,你可以定义一个 Responsive 类来处理不同屏幕尺寸的布局:

class Responsive {
  static bool isMobile(BuildContext context) =>
      MediaQuery.of(context).size.width < 600;

  static bool isTablet(BuildContext context) =>
      MediaQuery.of(context).size.width >= 600 &&
      MediaQuery.of(context).size.width < 1200;

  static bool isDesktop(BuildContext context) =>
      MediaQuery.of(context).size.width >= 1200;
}

然后在布局中使用:

class MyLayout extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    if (Responsive.isMobile(context)) {
      return MobileLayout();
    } else if (Responsive.isTablet(context)) {
      return TabletLayout();
    } else {
      return DesktopLayout();
    }
  }
}
回到顶部