Flutter响应式布局插件responsive_framework的使用

发布于 1周前 作者 yuanlaile 来自 Flutter

Flutter响应式布局插件responsive_framework的使用

简介

Screenshots

Responsive Framework 是一个帮助开发者构建响应式应用程序的Flutter插件,适用于移动设备、桌面和网站布局。它通过定义断点(breakpoints)来自动调整UI元素的大小和布局,使得开发者可以轻松创建适应不同屏幕尺寸的应用。

安装与配置

添加依赖

首先,在pubspec.yaml文件中添加responsive_framework作为依赖:

dependencies:
  flutter:
    sdk: flutter
  responsive_framework: ^latest_version

初始化应用

MaterialAppCupertinoApp中添加ResponsiveBreakpoints.builder,并定义断点:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      builder: (context, child) => ResponsiveBreakpoints.builder(
        child: child!,
        breakpoints: [
          const Breakpoint(start: 0, end: 450, name: MOBILE),
          const Breakpoint(start: 451, end: 800, name: TABLET),
          const Breakpoint(start: 801, end: 1920, name: DESKTOP),
          const Breakpoint(start: 1921, end: double.infinity, name: '4K'),
        ],
      ),
      initialRoute: '/',
      onGenerateRoute: (settings) => MaterialPageRoute(builder: (context) => MyHomePage()),
    );
  }
}

使用示例

响应式断点条件判断

根据定义的断点名称进行条件判断,以实现不同的UI逻辑:

if (ResponsiveBreakpoints.of(context).largerThan(MOBILE)) {
  // 当屏幕宽度大于移动端断点时执行的代码
  return FullWidthAppBarItems();
}

// 或者使用布尔值
if (ResponsiveBreakpoints.of(context).isDesktop) {
  // 当前是桌面端布局
  return DesktopLayout();
} else if (ResponsiveBreakpoints.of(context).isTablet) {
  // 当前是平板端布局
  return TabletLayout();
} else {
  // 当前是移动端布局
  return MobileLayout();
}

自定义断点

你可以根据需求自定义断点标签,并在代码中引用它们:

const customBreakpoints = [
  Breakpoint(start: 0, end: 450, name: MOBILE),
  Breakpoint(start: 451, end: 800, name: TABLET),
  Breakpoint(start: 801, end: 1920, name: DESKTOP),
  Breakpoint(start: 900, end: 900, name: 'EXPAND_SIDE_PANEL'), // 自定义断点
  Breakpoint(start: 1921, end: double.infinity, name: '4K'),
];

// 在页面中使用自定义断点
ExpandedSidePanel(expand: ResponsiveBreakpoints.of(context).largerThan('EXPAND_SIDE_PANEL'))

内置响应式组件

  • ResponsiveVisibility: 根据断点显示或隐藏子组件。
  • ResponsiveConstraints: 动态设置最大最小宽度高度约束。
  • ResponsiveRowColumn: 实现响应式的行或列布局。
  • ResponsiveGridView: 创建响应式的网格视图。
  • ResponsiveScaledBox: 按比例缩放内容。
  • MaxWidthBox: 控制最大宽度。

示例:使用ResponsiveVisibility隐藏特定断点下的按钮

ResponsiveVisibility(
  visible: ResponsiveBreakpoints.of(context).smallerThan(TABLET),
  child: ElevatedButton(onPressed: () {}, child: Text('仅在小屏显示')),
)

完整示例Demo

以下是一个完整的示例程序,展示了如何结合responsive_framework创建一个简单的响应式主页:

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

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'),
      builder: (context, widget) => ResponsiveBreakpoints.builder(
        child: widget!,
        breakpoints: [
          const Breakpoint(start: 0, end: 450, name: MOBILE),
          const Breakpoint(start: 451, end: 800, name: TABLET),
          const Breakpoint(start: 801, end: 1920, name: DESKTOP),
          const Breakpoint(start: 1921, end: double.infinity, name: '4K'),
        ],
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key? key, required this.title}) : super(key: key);

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

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            ResponsiveVisibility(
              visible: ResponsiveBreakpoints.of(context).largerThan(MOBILE),
              child: Text('This text only appears on larger screens.'),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

这个例子展示了如何通过ResponsiveBreakpoints.builder方法将整个应用包裹起来,并利用ResponsiveVisibility组件根据屏幕大小有条件地显示文本信息。


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

1 回复

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


当然,下面是一个关于如何使用Flutter中的responsive_framework插件来实现响应式布局的示例代码。responsive_framework插件允许开发者轻松地在不同的屏幕尺寸和方向上调整布局。

首先,确保你已经在pubspec.yaml文件中添加了responsive_framework依赖:

dependencies:
  flutter:
    sdk: flutter
  responsive_framework: ^0.1.4  # 请检查最新版本号

然后,运行flutter pub get来安装依赖。

接下来是一个简单的示例,展示如何使用ResponsiveWrapper来包裹你的应用,并根据屏幕尺寸和方向自动调整布局:

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

void main() {
  runApp(
    ResponsiveWrapper.builder(
      // 默认的宽度断点,可以根据需要调整
      defaultScale: 1.0,
      breakpoints: const [
        ResponsiveBreakpoint.resize(480),
        ResponsiveBreakpoint.resize(800),
        ResponsiveBreakpoint.resize(1200),
        ResponsiveBreakpoint.resize(1920),
      ],
      background: Container(color: Colors.grey[200]),
      child: MyApp(),
    ),
  );
}

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 使用ResponsiveBuilder来根据当前断点构建不同的布局
    return ResponsiveBuilder(
      builder: (context, sizingInformation) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Responsive Layout Demo'),
          ),
          body: LayoutBuilder(
            builder: (context, constraints) {
              if (sizingInformation.deviceScreenType == DeviceScreenType.mobile) {
                // 手机布局
                return Center(
                  child: Text(
                    'This is a mobile layout',
                    style: TextStyle(fontSize: 24),
                  ),
                );
              } else if (sizingInformation.deviceScreenType == DeviceScreenType.tablet) {
                // 平板布局
                return Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      'This is a tablet layout',
                      style: TextStyle(fontSize: 32),
                    ),
                    SizedBox(height: 20),
                    ElevatedButton(
                      onPressed: () {},
                      child: Text('Click Me'),
                    ),
                  ],
                );
              } else {
                // 桌面布局
                return Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      'This is a desktop layout',
                      style: TextStyle(fontSize: 40),
                    ),
                    SizedBox(width: 50),
                    ElevatedButton(
                      onPressed: () {},
                      child: Text('Action'),
                    ),
                    SizedBox(width: 50),
                    ElevatedButton(
                      onPressed: () {},
                      child: Text('Another Action'),
                    ),
                  ],
                );
              }
            },
          ),
        );
      },
    );
  }
}

在这个示例中,ResponsiveWrapper.builder被用来包裹整个应用,并定义了不同的断点。ResponsiveBuilder用于根据当前的屏幕尺寸和方向动态构建布局。sizingInformation.deviceScreenType可以用来判断当前的设备类型(手机、平板或桌面),并据此调整布局。

这个示例展示了基本的响应式布局方法,你可以根据需要进一步扩展和自定义布局。

回到顶部