Flutter屏幕适配插件responsive_context的使用

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

Flutter屏幕适配插件responsive_context的使用

responsive

这是一个响应式扩展,允许你在Flutter应用程序中指定屏幕和屏幕尺寸。你无需记住具体的宽度。

示例

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      initialRoute: '/',
      routes: {
        '/': (_) => DatePickerPage(),
      },
    );
  }
}

class DatePickerPage extends StatefulWidget {
  [@override](/user/override)
  _DatePickerPageState createState() => _DatePickerPageState();
}

class _DatePickerPageState extends State<DatePickerPage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Responsive Context"),
      ),
      body: SingleChildScrollView(
        child: Container(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                width: 600,
                // height: 600,
                // width: MediaQuery.of(context).size.width,
                child: LayoutBuilder(
                  builder: (ctx, constrain) {
                    // return Text("${!ctx.isExtraLarge? "HIDE" : "SHOW"}");
                    return GridView(
                      shrinkWrap: true,
                      padding: EdgeInsets.all(15),
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: constrain.isExtraSmall
                            ? 1
                            : constrain.isSmall
                                ? 2
                                : constrain.isMedium
                                    ? 3
                                    : constrain.isLarge ? 4 : 5,
                        crossAxisSpacing: 15,
                        mainAxisSpacing: 15,
                      ),
                      children: List.filled(
                        5,
                        Container(
                          color: Colors.blue,
                          alignment: Alignment.center,
                          child: Text(
                            "${constrain.screenSize} based on constrain",
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ).toList(),
                    );
                  },
                ),
              ),
              Container(
                width: 600,
                // height: 600,
                // width: MediaQuery.of(context).size.width,
                child: GridView(
                  shrinkWrap: true,
                  padding: EdgeInsets.all(15),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: context.isExtraSmall
                        ? 1
                        : context.isSmall
                            ? 2
                            : context.isMedium
                                ? 3
                                : context.isLarge ? 4 : 5,
                    crossAxisSpacing: 15,
                    mainAxisSpacing: 15,
                  ),
                  children: List.filled(
                    5,
                    Container(
                      color: Colors.red,
                      alignment: Alignment.center,
                      child: Text(
                        "${context.screenSize} based on context",
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ).toList(),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter屏幕适配插件responsive_context的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter屏幕适配插件responsive_context的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用responsive_context插件进行屏幕适配的代码案例。responsive_context插件可以帮助你更方便地在不同屏幕尺寸和分辨率上进行UI适配。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加responsive_context依赖:

dependencies:
  flutter:
    sdk: flutter
  responsive_context: ^0.1.0  # 请注意版本号,使用最新版本

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

2. 初始化插件

在你的应用的根MaterialAppCupertinoApp组件中,使用ResponsiveContextBuilder来包装你的应用。这通常在你的main.dart文件中完成。

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

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

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

3. 使用ResponsiveContext进行UI适配

现在你可以在任何组件中使用ResponsiveContext提供的方法来获取屏幕尺寸并进行适配。例如,你可以使用ResponsiveContext.of(context).size来获取当前屏幕尺寸,然后根据这个尺寸来设置你的UI组件的大小。

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final size = ResponsiveContext.of(context).size;
    
    return Scaffold(
      appBar: AppBar(
        title: Text('Responsive Context Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Screen Width: ${size.width.toStringAsFixed(2)} px',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            Text(
              'Screen Height: ${size.height.toStringAsFixed(2)} px',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            Container(
              width: size.width * 0.8, // 80% of screen width
              height: size.height * 0.4, // 40% of screen height
              color: Colors.blue,
              child: Center(
                child: Text(
                  'Responsive Box',
                  style: TextStyle(color: Colors.white, fontSize: 24),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

4. 响应式布局

你还可以使用ResponsiveContext提供的宽度和高度来创建响应式布局。例如,你可以根据屏幕尺寸动态调整组件的布局方式。

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

class ResponsiveLayoutPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final size = ResponsiveContext.of(context).size;
    
    return Scaffold(
      appBar: AppBar(
        title: Text('Responsive Layout Demo'),
      ),
      body: LayoutBuilder(
        builder: (context, constraints) {
          return Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              if (size.width > 600) // 假设大屏设备使用两栏布局
                Expanded(
                  child: Container(
                    color: Colors.red,
                    child: Center(child: Text('Column 1')),
                  ),
                ),
              Expanded(
                flex: size.width > 600 ? 1 : 2, // 小屏设备使用单栏布局,占据全部空间
                child: Container(
                  color: Colors.green,
                  child: Center(child: Text('Column 2')),
                ),
              ),
              if (size.width > 600)
                Expanded(
                  child: Container(
                    color: Colors.blue,
                    child: Center(child: Text('Column 3')),
                  ),
                ),
            ],
          );
        },
      ),
    );
  }
}

这个示例展示了如何使用ResponsiveContext根据屏幕尺寸动态调整布局。当屏幕宽度大于600像素时,使用三栏布局;否则,使用单栏布局。

这样,你就可以利用responsive_context插件在Flutter项目中轻松实现屏幕适配。

回到顶部