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

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

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

介绍

responsive_design 是一个用于创建响应式应用程序的Flutter插件,它允许你根据不同的屏幕尺寸使用不同的小部件。通过这个插件,你可以轻松地为桌面、平板、手机和手表等设备创建自适应的布局。

开始使用

添加依赖

pubspec.yaml 文件中添加 responsive_design 依赖:

dependencies:
  responsive_design:
重要更新

从版本 0.1.0 开始,ResponsiveSettings 类不再用于管理变更点。请改用 ScreenChangePoints,具体用法请参考示例代码。

自定义设置

你可以通过 ResponsiveSettings 类全局管理响应式的屏幕变更点:

void main() {
  // 全局设置
  ResponsiveSettings.instance.setCustomSettings(
    screenChangePoints: const ScreenChangePoints(
      desktopChangePoint: 1150.0,  // 桌面屏幕的变更点
      tabletChangePoint: 625.0,   // 平板屏幕的变更点
      watchChangePoint: 250.0,    // 手表屏幕的变更点
    ),
  );
  runApp(const MyApp());
}

使用响应式小部件

ResponsiveWidget 允许你为每个设备类型定义不同的布局:

const ResponsiveWidget(
  // 如果不设置全局值将被应用,如果不存在全局值,则默认值将被应用。
  screenChangePoints: ScreenChangePoints(),
  desktop: Scaffold(
    body: Center(
      child: Text(
        'Desktop screen',
        style: TextStyle(
          color: Colors.black,
          fontSize: 25.0,
        ),
      ),
    ),
  ),
  phone: Scaffold(
    body: Center(
      child: Text(
        'Phone screen',
        style: TextStyle(
          color: Colors.amber,
          fontSize: 25.0,
        ),
      ),
    ),
  ),
  tablet: Scaffold(
    body: Center(
      child: Text(
        'Tablet screen',
        style: TextStyle(
          color: Colors.greenAccent,
          fontSize: 25.0,
        ),
      ),
    ),
  ),
  watch: Scaffold(
    body: Center(
      child: Text(
        'Watch screen',
        style: TextStyle(
          color: Colors.blueAccent,
          fontSize: 25.0,
        ),
      ),
    ),
  ),
);

Responsive Widget

使用响应式应用栏

ResponsiveAppBar 可以让你的应用栏适应所有屏幕:

const Scaffold(
  appBar: ResponsiveAppBar(
    // 如果不设置全局值将被应用,如果不存在全局值,则默认值将被应用。
    screenChangePoints: ScreenChangePoints(),
    title: Text('Responsive app bar'),
    actions: [
      AppBarAction(
        Center(child: Text('About')),
      ),
      AppBarAction(
        SizedBox(width: 16.0),
        showInAllScreens: true,
      ),
      AppBarAction(
        Icon(Icons.brightness_auto_outlined),
        showInAllScreens: true,
      ),
      AppBarAction(
        SizedBox(width: 16.0),
        showInAllScreens: true,
      ),
    ],
  ),
);

Responsive App Bar

完整示例代码

以下是一个完整的示例代码,展示了如何使用 responsive_design 插件来创建一个响应式应用程序:

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

/// 主函数
void main() {
  // 全局设置
  ResponsiveSettings.instance.setCustomSettings(
    screenChangePoints: const ScreenChangePoints(
      desktopChangePoint: 1150.0,
      tabletChangePoint: 625.0,
      watchChangePoint: 250.0,
    ),
  );
  runApp(const MyApp());
}

/// 应用程序的根部
class MyApp extends StatelessWidget {
  /// 定义 [MyApp] 小部件
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Responsive Design Example',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        appBarTheme: const AppBarTheme(
          backgroundColor: Colors.blueGrey,
        ),
      ),
      routes: {
        '/': (_) => const HomePage(),
        '/responsive-app-bar': (_) => const ResponsiveAppBarExample(),
        '/responsive-widget': (_) => const ResponsiveWidgetExample(),
        '/sidebar-widget': (_) => const SidebarExample(),
      },
      initialRoute: '/',
    );
  }
}

/// 应用程序的主页
class HomePage extends StatelessWidget {
  /// 定义 [HomePage] 小部件
  const HomePage({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: ListView(
          children: [
            ListTile(
              onTap: () => Navigator.of(context).pushNamed('/responsive-app-bar'),
              title: const Text('Responsive App Bar'),
            ),
            ListTile(
              onTap: () => Navigator.of(context).pushNamed('/responsive-widget'),
              title: const Text('Responsive Widget'),
            ),
            ListTile(
              onTap: () => Navigator.of(context).pushNamed('/sidebar-widget'),
              title: const Text('Sidebar Widget'),
            ),
          ],
        ),
      ),
    );
  }
}

/// 响应式应用栏示例
class ResponsiveAppBarExample extends StatelessWidget {
  /// 定义 [ResponsiveAppBarExample] 小部件
  const ResponsiveAppBarExample({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const Scaffold(
      appBar: ResponsiveAppBar(
        screenChangePoints: ScreenChangePoints(),
        title: Text('Responsive app bar'),
        actions: [
          AppBarAction(
            Center(child: Text('About')),
          ),
          AppBarAction(
            SizedBox(width: 16.0),
            showInAllScreens: true,
          ),
          AppBarAction(
            Icon(Icons.brightness_auto_outlined),
            showInAllScreens: true,
          ),
          AppBarAction(
            SizedBox(width: 16.0),
            showInAllScreens: true,
          ),
        ],
      ),
    );
  }
}

/// 响应式小部件示例
class ResponsiveWidgetExample extends StatelessWidget {
  /// 定义 [ResponsiveWidgetExample] 小部件
  const ResponsiveWidgetExample({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const ResponsiveWidget(
      desktop: Scaffold(
        body: Center(
          child: Text(
            'Desktop screen',
            style: TextStyle(
              color: Colors.black,
              fontSize: 25.0,
            ),
          ),
        ),
      ),
      phone: Scaffold(
        body: Center(
          child: Text(
            'Phone screen',
            style: TextStyle(
              color: Colors.amber,
              fontSize: 25.0,
            ),
          ),
        ),
      ),
      tablet: Scaffold(
        body: Center(
          child: Text(
            'Tablet screen',
            style: TextStyle(
              color: Colors.greenAccent,
              fontSize: 25.0,
            ),
          ),
        ),
      ),
      watch: Scaffold(
        body: Center(
          child: Text(
            'Watch screen',
            style: TextStyle(
              color: Colors.blueAccent,
              fontSize: 25.0,
            ),
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用responsive_design插件来实现响应式设计的示例代码。responsive_design插件允许你根据屏幕尺寸和方向调整布局,使你的应用更加灵活和适应不同的设备。

首先,你需要在你的pubspec.yaml文件中添加responsive_framework依赖(注意:虽然你提到的是responsive_design,但通常较为流行且功能全面的插件是responsive_framework):

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

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

接下来,你可以在你的Flutter应用中使用ResponsiveWrapper来包裹你的MaterialApp或CupertinoApp。ResponsiveWrapper允许你定义不同屏幕尺寸和方向下的布局。

以下是一个完整的示例代码:

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 ResponsiveWrapper.builder(
      // 定义响应式设计的断点
      breakpoints: [
        ResponsiveBreakpoint.desktopSmall,
        ResponsiveBreakpoint.desktopMedium,
        ResponsiveBreakpoint.desktopLarge,
        ResponsiveBreakpoint.tablet,
        ResponsiveBreakpoint.watch,
        ResponsiveBreakpoint.phone,
      ],
      // 默认布局方向
      defaultScale: true,
      // 最小宽度和高度
      minimumWidth: 480,
      minimumHeight: 600,
      // 根据屏幕尺寸和方向变化的builder
      builder: (context, sizingInformation) {
        return MaterialApp(
          title: 'Flutter Responsive Design Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(sizingInformation: sizingInformation),
        );
      },
    );
  }
}

class MyHomePage extends StatelessWidget {
  final SizingInformation sizingInformation;

  MyHomePage({required this.sizingInformation});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Responsive Design Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Current Screen Size: ${sizingInformation.screenSize}',
              style: TextStyle(fontSize: sizingInformation.deviceScreenType == DeviceScreenType.desktop ? 24 : 18),
            ),
            SizedBox(height: 20),
            if (sizingInformation.orientation == DeviceOrientation.portrait)
              Image.network(
                'https://via.placeholder.com/300',
                width: sizingInformation.screenSize.width * 0.8,
              )
            else
              Image.network(
                'https://via.placeholder.com/600',
                width: sizingInformation.screenSize.width * 0.5,
              ),
          ],
        ),
      ),
    );
  }
}

在这个示例中:

  1. 我们使用ResponsiveWrapper.builder来包裹MaterialApp
  2. ResponsiveWrapper.builder中,我们定义了多个断点,这些断点用于确定设备的屏幕尺寸和方向。
  3. sizingInformation对象包含了关于当前屏幕尺寸、方向和设备类型的信息。
  4. MyHomePage中,我们根据sizingInformation动态调整文本的大小和图片的宽度,以实现响应式设计。

这个示例展示了如何根据屏幕尺寸和方向调整UI布局,但你可以根据具体需求进一步自定义和扩展。

回到顶部